Html 修改伪元素的 css 样式 :after content with Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7882325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modify css style for pseudo element :after content with Jquery
提问by Shara
I have baloon shape designed with CSS3.
JS Fiddle ExampleIt's have triangle made with
我有用 CSS3 设计的气球形状。
JS 小提琴示例它有三角形
:after {
content: "";
}
I need to moving triangle left-right with modify leftcss 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?
我需要使用 Jquery修改左css 参数来左右移动三角形。我知道我无法从 DOM 中选择伪元素,但是还有另一种方法可以更改 :after 样式与 js 吗?
Yes, we can put another div inside like
是的,我们可以在里面放另一个 div
<div class="pop"><div class="arr"></div></div>
but it's ugly
但它很丑
回答by csuwldcat
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 detailsthat contains a live example fiddle.
有一个更简单的方法:只需将伪元素的content
属性值设置为attr(some-attribute-name)
,它将使用父元素上的 HTML 属性值作为伪元素的内容。然后,您可以使用setAttribute()
父元素上的方法动态更改值。以下是此方法实际效果的模拟片段。我还写了一篇包含更多细节的博客文章,其中包含一个现场示例小提琴。
CSS
CSS
#SomeElement:after {
content: attr(some-attribute-name);
}
HTML
HTML
<div id="SomeElement" some-attribute-name="Pseudo content here!"></div>
JavaScript(to change pseudo content)
JavaScript(更改伪内容)
var someElement = document.getElementById('SomeElement');
someElement.setAttribute('some-attribute-name', 'New pseudo content here!');
回答by methodofaction
You insert the CSS styles dynamically in the head, and then modify that:
您在头部动态插入 CSS 样式,然后对其进行修改:
$("<style type='text/css' id='dynamic' />").appendTo("head");
$('.pop').click(function(e){
$("#dynamic").text(".pop:after{left:" + e.offsetX+ "px;}");
});
Here is a demo
这是一个演示
回答by nrabinowitz
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:
根据此相关问题,您无法选择伪元素。所以我建议定义额外的 CSS 类,并使用 jQuery 向气球添加类。例如使用这样的类:
.pop.right:after {
left: 80%;
}
and apply it like this:
并像这样应用它:
$('div.pop').addClass('right');
Working jsFiddle: http://jsfiddle.net/nrabinowitz/EUHAv/2/
工作 jsFiddle:http: //jsfiddle.net/nrabinowitz/EUHAv/2/