修改伪元素:使用javascript后的宽度

标记:

Hello World

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

 $.fn.textWidth = function(){ var html_org = $(this).html(); var html_calc = '' + html_org + ''; $(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属性。

为了按照你想要的方式获得你想要的效果,我最好的猜测是YUI.StyleSheet并操纵样式表本身,虽然我不得不承认我近年来没有自己测试过。

包括这样的实用程序并进行所有这些计算似乎对宽度匹配有很多工作。

如果您愿意在语义HTML上略微妥协,那么有一种可行的技术:

您的元素占据屏幕的整个宽度。 使用跨度包装文本并将伪元素添加到该文本,作为inline-block应该允许您仅在文本下获取边框

HTML:

 

Hello World

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属性的属性。

这样,如果推荐被批准和实施,则有可能让伪元素反映父项的属性,如下所示:

 this.setAttribute("length", $(this).textWidth()); 

和相关的CSS:

 .title:after { ... width: attr(length px); ... } 

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

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将width设置为inherit但其父级( .title )已覆盖min-width 。 现在我可以自由地通过JavaScript将宽度设置为标题,它只对他的嵌套伪元素生效:

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

这是一个不同的方法…… http://jsfiddle.net/mayYt/

添加了CSS

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

JQuery的

 $('.title').wrapInner(''); 

只需一个简单的技巧,任何伪元素都可以更改(或者至少替换为其他元素):

 $('.something').click(function(){ $(this).toggleClass('to_show'); }); 
 .something { background: red; height: 40px; width: 120px; position: relative; } .something.to_show:after { content: "X"; color: white; background: green; width: 20px; height: 20px; position: absolute; right: 0px; top: 0px; display: block; text-align: center; } .something:after { content: "O"; color: white; background: blue; width: 30px; height: 25px; position: absolute; right: 0px; top: 0px; display: block; text-align: center; } 
    
click here!