您现在的位置是:首页 > Javascript
当前栏目
js 动态修改_after_before伪元素content值
2023-03-15 23:25:47 时间
今天做了一个有关js如何绑定动态修改伪类的content的内容,运用到的有( :before 和 :after 伪元素、CSS content 属性、data-* H5新属性、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)最后通过js获取到box对象,通过box对象attributes
找到添加的 [data-content-before=":before"]和[ data-content-after=":after"]属性的value,有了value值,这就可以进行动态修改 before伪元素和:after 伪元素里的content值; 以此现在做一个笔记以便以后使用,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 type="text/javascript">
var box = document.getElementById('box');
var boxBeforeVal = box.attributes[1].value;
var boxAfterVal = box.attributes[2].value;
//console.log(boxBefore);//输出为 :before
//console.log(boxAfter);//输出为 :after
//下面可以自定义boxBeforeVal和boxAfterVal的值
box.attributes[1].value = ':before伪元素';
box.attributes[2].value = ':after伪元素';
</script>
相关文章
- TiDB Binlog 组件正式开源
- 使用Visual Studio Code对Node.js进行断点调试
- 推荐!数据可视化的十种优秀JavaScript图表库
- Node.js在复杂集成场景下占据统治地位的五个理由
- 玩转Node.js单元测试
- Node.js中内存泄漏分析
- Angular对React:一场关于Web开发者支持率的史诗对决
- 热点推荐:什么是后端开发?
- 谈谈Spring boot 启动层面的开发
- 使用NodeJS将文件或图像上传到服务器
- 编写React组件的最佳实践
- JavaScript MV*框架最值得关注的七个亮点
- 前端开发指南:如何利用PHP Cake框架构建应用
- 基于React与Vue后,移动开源项目Weex如何定义未来
- NodeJS和C++之间的类型转换
- jQuery中的常用到的三十九个技巧
- 官宣|Google Developers中国网站发布!
- NodeJS和C++之间的类型转换
- .NET Core首例Office开源跨平台组件(NPOI Core)
- 如何写出漂亮的React组件