web前端

jquery动态修改:after:before伪元素conten

2021-01-07  本文已影响0人  一岁倾城

根据昨天做的js动态修改:after:before伪元素content值,今天拓展一些jquery如何绑定动态修改伪类的content的内容,运用到的有( :before 和 :after 伪元素、CSS content 属性、data-* H5新属性、jquery)等技术。
基本原理跟js很相似,不过jquery的方法很简单,只需要一个attr方法就可以实现,不像js还有一步一步等操作,部分方便大家观看,再把基本原理放出来吧。— —+
基本原理:
1)首先给box盒子添加 [data-content-before=":before"]和[ data-content-after=":after"]属性;
2)其次添加html标签和style样式;
3)在样式里添加box元素的:before伪元素和:after 伪元素;
4):before伪元素和:after 伪元素里各自添加content属性;
5)content 和 attr 配合使用:
content: attr(data-content-after);content: attr(data-content-before);
这样content可以获取到box添加data-content-after属性里的值:after(before同理)
6)最后通过jquery取到box对象,通过box对象attr(attribute,value)“attribute”是属性参数,“value”是要替换内容参数;
以此现在做一个笔记以便以后使用,Hope to help you.

废话不多说,直接上代码

一、html代码部分

<div id="box" data-content-before=":before" data-content-after=":after">box盒子</div>

二、css样式部分

<style>
    *{
        padding: 0;
        margin: 0;
    }
    body{
        padding: 0;
        margin: 0;
    }
    #box{
        width: 200px;
        height: 200px;
        position: fixed;
        top: calc(50% - 100px);
        left: calc(50% - 100px);
        background: #0877FF;
        border-radius: 10px;
        text-align: center;
        box-shadow: 1px 2px 3px -1px;
    }
    #box:after{
        content: attr(data-content-after);
        position: relative;
        top: -120px;
        left: -160px;
        width: 104px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        border-radius: 10px;
        background: orange;
        box-shadow: 1px 2px 3px -1px;
        display: block;
    }
    #box:before{
        content: attr(data-content-before);
        position: relative;
        top: 0;
        right: -260px;
        width: 104px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        border-radius: 10px;
        background: #39c778;
        box-shadow: 1px 2px 3px -1px;
        display: block;
    }
</style>

三、js代码部分


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    //jquery直接用attr方法替换,简单粗暴;
    $('#box').attr("data-content-before",':before伪元素');
    $('#box').attr("data-content-after",':after伪元素');
</script>

四、效果图

刷新页面前.png 刷新页面后.png

五、其他
有小伙伴对js动态修改:after:before伪元素content值实现感兴趣的话,请参考这个网址:
https://www.jianshu.com/p/0d1f0d482e81

上一篇 下一篇

猜你喜欢

热点阅读