js動態修改:after:before偽元素content值
阿新 • • 發佈:2021-01-06
總覽
今天做了一個有關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 偽元素;
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.
廢話不多說,直接上程式碼
一、效果圖
二、程式碼區域
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js動態修改:after:before偽元素content值</title>
<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>
</head>
<body>
<div id="box" data-content-before=":before" data-content-after=":after">box盒子</div>
<script type="text/javascript">
//js用法
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>
</body>
</html>