怎么用javascript获得一个元素的伪元素

JavaScript013

怎么用javascript获得一个元素的伪元素,第1张

可以通过window.getComputedStyle方法获取到伪元素;比如获取h1元素的before伪元素

var before = window.getComputedStyle(document.getElementsByTagName("h1")[0], ':before')

首先伪元素(pseudo-element)应该是CSS相关的概念。 现有的浏览器支持或尚未支持的伪元素如下: ::after ::before ::first-letter ::first-line ::selection ::backdrop ::placeholder ::marker ::sp

方法一,完全用js模拟(这样太麻烦)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

        .css1{

            width: 100px

            height: 200px

            border: 1px solid black

        }

        .css1:hover

 {

            border: 2px solid red

        }

    </style>

</head>

<body>

<div>这是一个div</div>

<script>

    var div = document.getElementsByTagName("div")[0]

    div.style.cssText = "border:1px solid redwidth:100pxheight:100px"

    div.onmouseover = function () {

        div.style.cssText = "border:1px solid blackwidth:100pxheight:100px"

    }

    div.onmouseout = function () {

        div.style.cssText = "border:1px solid redwidth:100pxheight:100px"

    }

</script>

</body>

</html>

2.方法二:js加css,还是麻烦

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

        .css1{

            width: 100px

            height: 200px

            border: 1px solid black

        }

        .css1:hover

 {

            border: 2px solid red

        }

    </style>

</head>

<body>

<div>这是一个div</div>

<script>

//    var div = document.getElementsByTagName("div")[0]

//    div.style.cssText = "border:1px solid redwidth:100pxheight:100px"

//    div.onmouseover = function () {

//        div.style.cssText = "border:1px solid blackwidth:100pxheight:100px"

//    }

//    div.onmouseout = function () {

//        div.style.cssText = "border:1px solid redwidth:100pxheight:100px"

//    }

 var div = document.getElementsByTagName("div")[0]

      div.setAttribute("class","css1")

</script>

</body>

</html>

其实完全可以不用js来设置css,这样会比较麻烦,最直接的方法就是在元素里面直接设置class,在style或者css文件里面定义样式,如果有伪类这些也可以写在里面就好。