修改伪选择:在javascript之后 [英] modify pseudo select :after in javascript

查看:77
本文介绍了修改伪选择:在javascript之后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个css,如

I have defined a css like

.slidingTag li:after {
  content: '';
  z-index: 3;
  height: 6px;
}

我想从JS动态更改height属性。我可以使用

I want to change the height attribute dynamically from JS. I can get the property using

window.getComputedStyle(document.querySelector('.slidingTag'), 'li:after').getPropertyValue('height')

但我不知道如何更改height属性。我试图使用 setProperty ,但似乎没有这样的函数可用于伪类。任何想法让我知道。

But I do not know how to change the height attribute. I tried to use setProperty but it seems there is no such function available for pseudo-classes. Any ideas let me know.

推荐答案

如果该样式来自CSS文件,则必须在 document.styleSheets ,其中会很混乱。

If that style comes from a CSS file, you'll have to search for it in document.styleSheets, which will be messy.

如果您愿意动态创建一个包含该CSS的< style> 元素,你可以通过编程方式修改它。

If you are open to dynamically creating a <style> element containing that CSS instead, you can modify it programmatically.

var slidingTagLiAfterStyle = document.createElement("style");
slidingTagLiAfterStyle.innerHTML =
 ".slidingTag li:after {
    content: '';
    z-index: 3;
    height: 6px;
  }";
document.head.appendChild(slidingTagLiAfterStyle);

...

slidingTagLiAfterStyle.innerHTML = slidingTagLiAfterStyle.innerHTML.replace(/height: [0-9]+px/, "height: 12px"); // or whatever you want to set it to

这篇关于修改伪选择:在javascript之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆