简体   繁体   English

jQuery和伪元素

[英]jQuery and pseudo-elements

I tried to dynamically change the position of an element which is defined in CSS with :after . 我尝试动态更改CSS中定义的元素的位置:after Using this: 使用这个:

$(function(){
    $('div::after').css({'top':'20px'})
})

But it doesn't work. 但它不起作用。 Are there any ways to change the position? 有没有办法改变立场?

You can't. 你不能。 Content created by :after or :before is not part of the DOM and therefore cannot be selected or modified. 创建的内容:after:before不是DOM的一部分,因此无法选择或修改。

If you have a look at this example fiddle and inspect the DOM in Firebug or similar you will see that the pseudo-element is not present in the DOM tree. 如果您查看此示例 ,请在Firebug或类似文件中查看并检查DOM,您将看到DOM树中不存在伪元素。

A potential solution would be to apply a class to the element you want to change, and to style that class appropriately in CSS: 一个潜在的解决方案是将类应用于您想要更改的元素,并在CSS中适当地设置该类的样式:

$("div").addClass("newClass");

See this fiddle for an example . 一下这个小提琴的例子

add CSS: 添加CSS:

p.special:before {
    content: "bar";
    position: absolute;
    top : 10px;
}

assuming the style sheet where the code above was put is the first one on the page, use this to change it: 假设上面放置代码的样式表是页面上的第一个代码,使用它来更改它:

document.styleSheets[0].addRule('p.special:before','top: 15px;');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM