问题是要修改
::after
伪元素的样式。
点击::after
时,我想更改其背景颜色样式;
但是尝试了一些方法之后我无法获得该伪元素,该怎么办?
getComputedStyle(document.querySelector(`[data-uid="circle3"]`), "::after").setProperty("background-color", "rgb(255, 0, 255)");
// VM15036:1 Uncaught DOMException: Failed to execute 'setProperty' on 'CSSStyleDeclaration': These styles are computed, and therefore the 'background-color' property is read-only.
at <anonymous>:1:77
let three = document.querySelector(`[data-uid="circle3"]`);
// <div data-uid="circle3" class="tips tips2 rotate">…</div>
three.querySelector(`::after`);
document.querySelector(`[data-uid="circle3"]::after`);
// null
document.querySelector(`[data-uid="circle3"]`).querySelector(`::after`);
// null
document.querySelector(`[data-uid="circle3"]`).setAttribute(`::after`, "background", "red");
// undefined
document.querySelector(`[data-uid="circle3"]`)["::after"].setAttribute("background", "red");
// VM16539:1 Uncaught TypeError: Cannot read property 'setAttribute' of undefined
at <anonymous>:1:58
(anonymous) @ VM16539:1
let textareas = [...document.querySelectorAll(`[data-uid^="circle"]`)];
let btn = document.querySelector(`[data-uid="btn"]`);
btn.addEventListener(`click`, () => {
textareas.forEach((textarea, i) => {
textarea.setAttribute(`class`, `tips tips${i} rotate`);
});
});
// let center = 2;
textareas.forEach((textarea, i) => {
textarea.addEventListener(`click`, () => {
for (const item of textareas) {
item.classList.remove(`tips-highlight`);
}
textarea.classList.add(`tips-highlight`);
});
});
.tips::after {
content: "";
position: absolute;
left: 50%;
top: -19%;
height: 30px;
width: 30px;
background-color: #00c991;
border-radius: 50% 50% 0;
transform: translate(-50%, -50%) rotate(45deg);
}
.tips-highlight::after {
background-color: #f82eb5;
}
https://codepen.io/xgqfrms/full/rEOdBw