这个问题在这里已经有了答案:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(25 个回答)
1年前关闭。
如何将 CSS 更改为伪元素样式?
我正在尝试获取 CSS before::
规则和改变left:
至95%
或 4px
.
如何在我的上下文中执行此操作?
我还使用 document.querySelector
进行了一些测试但它不起作用,我得到一个计算只读错误。
你有什么建议吗?
Example:
css
.iziToast-wrapper-bottomLeft .iziToast.iziToast-balloon:before {
border-right: 15px solid transparent;
border-left: 0 solid transparent;
right: auto;
left: 8px;
}
js
if(description_iziToast){
let RightMode = event.x>window.innerWidth/2;
let bubblePosition = document.getElementsByClassName("iziToast-balloon")[0]; // get the div that hold the bubble
let ajustScreenLR = RightMode && document.getElementsByClassName("iziToast")[0].offsetWidth || 0; // halfScreen ajustement
//bubblePosition.style.left = RightMode && '95%' || '4px'; // here i need to change the position in the befor:: attribut
description_iziToast.style.left = `${event.x-20-ajustScreenLR}px`;
description_iziToast.style.top = `${event.y-105}px`;
}
}else{
if(description_iziToast){ iziToast.destroy(); description_iziToast = false; };
}
这里是应用程序控制台调试
最佳答案
由于 DOM 中不存在伪元素,因此无法在 Javascript 中访问它们。
解决方法是创建一个 <span>
而不是使用:before
并且必须应用相同的逻辑。
关于javascript - 从 javascript 更改伪元素样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49106088/