使用JavaScript获取伪元素属性

    技术2022-07-11  134

    CSS pseudo-elements are incredibly useful -- they allow us to create CSS triangles for tooltips and perform a number of other simple tasks while preventing the need for additional HTML elements.  To this point, these pseudo-element CSS properties have been unreachable by JavaScript but now there's a method for getting them!

    CSS伪元素非常有用-它们使我们能够为工具提示创建CSS三角形 ,并执行许多其他简单任务,同时避免了对其他HTML元素的需求。 至此,JavaScript无法访问这些伪元素CSS属性,但是现在有一种获取它们的方法!

    Assume your CSS looks like:

    假设您CSS看起来像:

    .element:before { content: 'NEW'; color: rgb(255, 0, 0); }

    To retrieve the color property of the .element:before, you could use the following JavaScript:

    要检索.element:before的color属性,可以使用以下JavaScript:

    var color = window.getComputedStyle( document.querySelector('.element'), ':before' ).getPropertyValue('color')

    Passing the pseudo-element as the second argument to window.getComputedStyle allows access to said pseudo-element styles!  Keep this snippet in your toolbox for years to come -- pseudo-elements will only grow more useful with broader browser support!

    将伪元素作为第二个参数传递给window.getComputedStyle允许访问所述伪元素样式! 将此代码段保存在您的工具箱中数年之久-伪元素只有在更广泛的浏览器支持下才会变得越来越有用!

    翻译自: https://davidwalsh.name/pseudo-element

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.010, SQL: 9