如何使用JavaScript修改DOM元素的:: after样式?

时间:2019-06-14 02:01:48

标签: javascript dom css-selectors pseudo-element

  

问题是要修改::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

裁判

https://stackoverflow.com/a/14106897/5934465

0 个答案:

没有答案