Modify css style for pseudo element :after content with Jquery

折月煮酒 提交于 2019-11-30 10:29:40

问题


I have baloon shape designed with CSS3.
JS Fiddle Example It's have triangle made with

:after {
    content: "";
}

I need to moving triangle left-right with modify left css param with Jquery. I know that i can't select pseudo element which out of DOM, but is there another way to change :after style with js?

Yes, we can put another div inside like

<div class="pop"><div class="arr"></div></div>

but it's ugly


回答1:


There is a much easier way: just set the pseudo element's content property value to attr(some-attribute-name), it will use the value of the HTML attribute on the parent as the content for the pseudo element. You can then use the setAttribute() method on the parent element to change the value dynamically. Below are mock snippets of how this method would look in action. I also did a blog post with further details that contains a live example fiddle.

CSS

#SomeElement:after {
    content: attr(some-attribute-name);
}

HTML

<div id="SomeElement" some-attribute-name="Pseudo content here!"></div>

JavaScript (to change pseudo content)

var someElement = document.getElementById('SomeElement');
someElement.setAttribute('some-attribute-name', 'New pseudo content here!');



回答2:


You insert the CSS styles dynamically in the head, and then modify that:

$("<style type='text/css' id='dynamic' />").appendTo("head");

$('.pop').click(function(e){
  $("#dynamic").text(".pop:after{left:" + e.offsetX+ "px;}");
});

Here is a demo

http://jsfiddle.net/HWnLd/




回答3:


As per this related question, you can't select the pseudo element. So I'd suggest defining additional CSS classes, and adding classes to the balloon with jQuery. E.g. use a class like this:

.pop.right:after {
    left: 80%;   
}

and apply it like this:

$('div.pop').addClass('right');

Working jsFiddle: http://jsfiddle.net/nrabinowitz/EUHAv/2/



来源:https://stackoverflow.com/questions/7882325/modify-css-style-for-pseudo-element-after-content-with-jquery

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