13

マークアップ:

<h1 class="title">Hello World</h1>

CSS:

.title {
  border-bottom: 3px solid #aaa;
  position: relative;
}
.title:after {
  content: "";
  width: 100px;
  border-bottom: 3px solid red;
  display: block;
  position: absolute;
}

デモ: http://codepen.io/anon/pen/HDBqe

.title:afterテキストの幅に基づいて の幅を変更したかったのですが、 :afterjavascript を使用して の幅を変更するにはどうすればよいですか?

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

$('.title').each(function(){
  // Change :after's width based on the text's width
  // .css('width', $(this).textWidth());
});
4

4 に答える 4

16

この場合に機能するトリックを見つけました。私はあなたのデモを更新しました:

http://codepen.io/anon/pen/bHLtk

.title {
  border-bottom: 3px solid #aaa;
  position: relative;
  min-width: 100%;
}

.title:after {
  content: "";
  width: inherit;
  border-bottom: 3px solid red;
  display: block;
  position: absolute;
}

.title:afterwidth が に設定されていますinheritが、親 ( .title) が でオーバーライドさwidthれていることに注意してくださいmin-width。これで、JavaScript を使用して自由に幅をタイトルに設定できるようになり、ネストされた疑似要素でのみ有効になります。

$('.title').each(function(){
  $(this).css('width', $(this).textWidth());
});
于 2014-02-12T21:16:23.563 に答える
1

これは別のアプローチではどうですか.... http://jsfiddle.net/mayYt/

追加された CSS

.title span {
    border-bottom: 3px solid red;
}

JQuery

$('.title').wrapInner('<span />');
于 2013-09-09T11:33:24.903 に答える