Dynamically styling pseudo-elements using jQuery or Javascript

两盒软妹~` 提交于 2020-01-02 12:42:11

问题


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.

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.

How can I achieve this?

Thanks in advance

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

回答1:


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

Usage

loadStyle('p.clicker::after { margin-top: ' + calculated-value + 'px; }');

Script

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)



来源:https://stackoverflow.com/questions/43138544/dynamically-styling-pseudo-elements-using-jquery-or-javascript

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