jQuery and pseudo-elements

房东的猫 提交于 2019-12-27 15:41:27

问题


I tried to dynamically change the position of an element which is defined in CSS with :after. Using this:

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

But it doesn't work. Are there any ways to change the position?


回答1:


You can't. Content created by :after or :before is not part of the DOM and therefore cannot be selected or modified.

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.

A potential solution would be to apply a class to the element you want to change, and to style that class appropriately in CSS:

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

See this fiddle for an example.




回答2:


add 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;');


来源:https://stackoverflow.com/questions/8968992/jquery-and-pseudo-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!