LoginSignup
0
2

More than 5 years have passed since last update.

字詰め(カーニング)簡易js (imgのalt属性対応)

Last updated at Posted at 2017-06-21

字詰めにはいくつかライブラリがありますが、簡易版をスニペットとして。

ざっくりとブロック全体に字詰めjsを適用した時、画像が含まれていると
imgのalt属性内までspanタグが入ってしまいソースが崩れてしまうので
少々トリッキーですがURIEncodeで回避しています。

字詰めの具合はCSSに書いてよしなにしてくださいまし〜。

/**
 * 字詰め(カーニング)js
 * 
 * ex.) _kerning($("#contents"));
 * css) .kerning-before { display: inline-block; margin-left: -0.4em; }
 *      .kerning-after { letter-spacing: -0.2em; }
 */
function _kerning($obj){

    // save for alt
    $("img", $obj).each(function(){
        $(this).attr({ alt: encodeURIComponent($(this).attr("alt")) });
    });

    // 字詰め
    var html = $obj.html();
    html = html.replace(/([「『([{〈《【〔])/g, '<span class="kerning-before">$1</span>');
    html = html.replace(/([」』)]}〉》】〕、,。.])/g, '<span class="kerning-after">$1</span>');
    $obj.html(html);

    // restore for alt
    $("img", $obj).each(function(){
        $(this).attr({ alt: decodeURIComponent($(this).attr("alt")) });
    });

}
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2