前端开发,怎么用js给节点添加伪元素

JavaScript08

前端开发,怎么用js给节点添加伪元素,第1张

CSS部分:

<style>

    .p::after{

        content: "Hello"

        color: red

    }

</style>

JS部分:

<script>

    var p = document.querySelector('p')

    p.setAttribute('class','p')

</script>

HTML部分:

<p></p>

方法一,完全用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文件里面定义样式,如果有伪类这些也可以写在里面就好。