修改伪元素:后边的宽度使用javascript [英] Modify pseudo-element :after's width using javascript
问题描述
标记:
<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? / p>
I wanted to change the .title:after
's width based on the text's width, how do I change :after
's width using javascript?
$.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());
});
推荐答案
伪元素不是DOM的一部分。因此,您无法通过JS直接更改其CSS属性。
A pseudo-element is not part of the DOM. Therefore, you cannot change its CSS properties directly through JS.
为了以您想要的方式获得所需的效果,我最好的猜测将 YUI.StyleSheet 并操纵样式表本身,虽然我不得不承认我没有
In order to get your desired effect the way you want it, my best guess would be YUI.StyleSheet and manipulate the stylesheet itself, although I have to admit I haven't tested it myself in recent years.
包括这样一个实用程序,做所有这些计算似乎很多工作宽度匹配。
Including such a utility and doing all of this calculation seems like a lot of work for width matching.
如果你愿意在语义HTML上有所妥协,有一个工作方法:
If you are willing to compromise a little bit on the semantic HTML, there is a working technique:
你的元素占用整个宽度屏幕。使用span来包装文本并添加伪元素,因为 inline-block
应该允许您只在文本下获取边框
Your element takes the entire width of the screen. Wrapping the text with a span and adding the pseudo-element to that, as an inline-block
should allow you to get the border under the text only
HTML:
<h1 class="title"><span>Hello World</span></h1>
CSS:
.title {
border-bottom: 3px solid #aaa;
position: relative;
}
.title span{
display:inline-block;
position:relative;
}
.title span:after {
content: "";
width: 100%;
border-bottom: 3px solid red;
display: block;
position: absolute;
}
这里是我的版本的codePen 。
有 W3C候选建议表明,使用 content
以外的CSS属性的属性。
There is a W3C Candidate Recommendation that suggests the capability of using attributes for CSS properties other than content
.
这样,如果并且当推荐被批准和实现时,可能有伪元素反映父属性的属性,例如:
This way, if and when the recommendation is approved and implemented, it might be possible to have the pseudo-element reflect the parent's attributes, as such:
this.setAttribute("length", $(this).textWidth());
和相关的CSS:
.title:after {
...
width: attr(length px);
...
}
这篇关于修改伪元素:后边的宽度使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!