通过JavaScript改变CSS伪元素样式 [英] Changing CSS pseudo-element styles via JavaScript

查看:205
本文介绍了通过JavaScript改变CSS伪元素样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过JavaScript更改CSS伪元素样式?



例如,我想动态设置滚动条的颜色,如: p>

  document.querySelector(#editor ::  -  webkit-scrollbar-thumb:vertical)。style.background = localStorage.getItem 颜色); 

,我也希望能够让滚动条隐藏:

  document.querySelector(#editor ::  -  webkit-scrollbar)style.visibility =hidden; 

但是,这两个脚本都返回:


未捕获的TypeError:无法读取属性style为null




跨浏览器互操作性并不重要,我只需要在webkit浏览器中工作。

解决方案

:技术上是通过JavaScript直接更改CSS伪元素样式的一种方式,这个答案描述了,但请永远不要这样做。这是解决这个问题的错误方法。


最接近在JavaScript中改变伪元素的样式是添加和删除类,然后使用伪元素与那些类。隐藏滚动条的示例:



CSS

  .hidden-scrollbar ::  -  webkit-scrollbar {
visibility:hidden;
}

JavaScript

  document.getElementById(editor)。classList.add('hidden-scrollbar'); 

要稍后删除同一个类,可以使用:

  document.getElementById(editor)。classList.remove('hidden-scrollbar'); 


Is it possible to change a CSS pseudo-element style via JavaScript?

For example, I want to dynamically set the color of the scrollbar like so:

document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");

and I also want to be able to tell the scrollbar to hide like so:

document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";

Both of these scripts, however, return:

Uncaught TypeError: Cannot read property 'style' of null

Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.

解决方案

EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but please never, ever do that. It's the wrong way to solve this problem.

The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:

CSS

.hidden-scrollbar::-webkit-scrollbar {
   visibility: hidden;
}

JavaScript

document.getElementById("editor").classList.add('hidden-scrollbar');

To later remove the same class, you could use:

document.getElementById("editor").classList.remove('hidden-scrollbar');

这篇关于通过JavaScript改变CSS伪元素样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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