使用jQuery或Javascript动态设计伪元素 [英] Dynamically styling pseudo-elements using jQuery or Javascript
问题描述
我需要在每次点击图片时动态更改 p :: p
前的 margin-top
值。
这两个问题都没有 1 / 2 / 3 / 4 也不是教程对我有用,因为我正在更改 margin-top
值不是内容或颜色。
I need to change the margin-top
value of p::before
dynamically on each image click.
Neither of these questions 1 / 2 / 3 / 4 nor this tutorial worked for me since I am changing the margin-top
value not content or colors.
我不能使用 attr()
因为根据这个。
创建样式表或添加脚本的标题不是一个好主意,因为我无法再次访问和修改它,因此它创建了数十个样式标记和规则并且它正在搞乱我的造型。
I can't use attr()
because it's not supported for non-string values according to this.
Creating stylesheet or adding scripting the the header isn't a good idea since I can't reach and modify it again so it's creating tens of style tags and rules and it's messing up with my styling.
我如何实现这一目标?
提前致谢
p::after {
top: auto;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
border-bottom-color: #f9e8a2;
border-width: 15px;
left: 50%;
margin: 28px 0 0 -15px;
}
推荐答案
我建议这样做,动态创建样式
元素(带有唯一ID,以便您可以反复访问)并且只是反复更新规则
May I suggest doing like this, where you dynamically create a style
element (with a unique id so you can access it over and over) and just update a rule repeatedly
用法
loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');
脚本
function loadStyle(css) {
var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
style.id = 'lastinbody';
style.type = 'text/css';
if (style.styleSheet){
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.querySelector('body').appendChild(style);
}
我的这篇文章还有几个版本(可能会被视为可能重复)
At this post of mine is a few more versions (which might be consider as a possible duplicate)
这篇关于使用jQuery或Javascript动态设计伪元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!