如何用JQuery操作CSS伪文档元素before或after中的content

html-css013

如何用JQuery操作CSS伪文档元素before或after中的content,第1张

::before,::after是伪元素并非doom元素,所以jquery无法选择伪元素。

如果确实需要实现修改伪元素的样式,可以通过下面的例子。

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>pseudo-elements test by zhou2003737</title>

    <style type="text/css">

        p{

            color: deepskyblue

        }

        p:before{

            content: attr(data-beforeContent)

            color: darkred

        }

    </style>

</head>

<body>

    <p data-beforeContent="测试">1111</p>

</body>

<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript">

    $(function(){

        <!--使用jquery1.8之前版本 click方法更改为toggle-->

             var times = 0

            $('p').on('click',function(){

                switch (times){

                    case 0:

                        $(this).attr('data-beforeContent','你说啥都是对的')

                        times++

                        break

                    case 1:

                        $(this).attr('data-beforeContent','你这么叼咋不上天呢')

                        times++

                        break

                    case 2:

                        $(this).attr('data-beforeContent','那就上天吧')

                        times++

                        break

                    default :

                        times =0

                        $(this).attr('data-beforeContent','你说啥都是对的')

                        times++

                        break

                }

            })

    })

</script>

</html>

首先我们看一下css伪元素是什么:

CSS 伪元素用于向某些选择器设置特殊效果。

伪元素有哪些:

:first-line 伪元素:"first-line" 伪元素用于向文本的首行设置特殊样式。

:first-letter 伪元素:"first-letter" 伪元素用于向文本的首字母设置特殊样式。

:before 伪元素:":before" 伪元素可以在元素的内容前面插入新内容。

:after 伪元素:":after" 伪元素可以在元素的内容之后插入新内容。

伪元素例子:

.flow_ball1:after {

content: ""

position: absolute

top: 50%

margin-top: -1px

left: 100%

margin-left: 0.133333rem

width: 1.786667rem

height: 2px

background-color: #ff6600

border-radius: 0.053333rem

在名为flow_ball1的class标签后面添加一道橘色横线(类似于流程图那种)

那么,问题来了,怎么用jquery改变伪元素的样式呢?

答案在这里:

$('.flow_ball1').append("<style>#fafang::after{display:none}</style>")