使用 jQuery 或 Javascript 动态设置 pseudo-elements 样式

Dynamically styling pseudo-elements using jQuery or Javascript

我需要在每次点击图片时动态更改 p::beforemargin-top 值。 这些问题 1 / 2 / 3 / 4 nor this tutorial 都不适合我,因为我正在更改 margin-top 值而不是内容或颜色。

我无法使用 attr(),因为根据 this,non-string 值不支持它。 创建样式表或在 header 中添加脚本不是一个好主意,因为我无法访问并再次修改它,所以它创建了数十个样式标签和规则,并且弄乱了我的样式。

我怎样才能做到这一点?

提前致谢

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;
}

我可以建议这样做,动态创建一个 style 元素(具有唯一 ID,以便您可以一遍又一遍地访问它)并重复更新规则

用法

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);
}

this post of mine 处还有几个版本(可能被认为是重复版本)