javascript - 修改伪元素:after's width using javascript

标签 javascript jquery css

<分区>

标记:

<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 的宽度,如何使用 javascript 更改 :after 的宽度?

$.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());
});

最佳答案

我发现了一个适用于这种情况的技巧。我已经更新了你的演示:

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:after 的宽度设置为 inherit 但他的父级 (.title) 已覆盖 widthmin-width。现在我可以自由的通过JavaScript给title设置width了,并且只对他嵌套的伪元素生效:

$('.title').each(function(){
  $(this).css('width', $(this).textWidth());
});

关于javascript - 修改伪元素:after's width using javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18694168/

相关文章:

javascript - 遇到循环问题

jquery - 位置固定的 Div,直到特定高度出现故障

css - 更多/更少分页 Angular 动画

html - 阶梯 Div 格式

javascript - 多个 div 的 jQuery 范围 slider 值框

html - 图片上的文字

javascript - 解析 JavaScript 中的日期字符串以获取时区偏移量

javascript - 如何在两个字段更改时启用按钮。

javascript - React Router 和历史

javascript - "This"正在返回 [object Window],而不是元素