js控制偽元素
- 1.通過attr()改變偽元素的值
- 2.覆寫原有樣式
- (1)css優先級覆寫
- (2)更改class類名覆寫
- (3)行內樣式表覆寫
大家應該知道js是不能直接控制偽元素的,所以總結了倆方法,下面是未改變前的代碼和實作效果,
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 300px;height: 200px;border: 5px solid black;margin: 100px auto;
}
.box:before{
content: '阿花';color: red;font-size: 24px;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>

1.通過attr()改變偽元素的值
偽元素通過attr()來獲取標簽自定義屬性的值,這個方法的缺點就是只能改變偽元素的值,而不能改變偽元素的屬性,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
<style>
.box{
width: 300px;height: 200px;border: 5px solid black;margin: 100px auto;
}
.box:before{
content: attr(dataBefore);color: red;font-size: 24px;
}
</style>
</head>
<body>
<div class="box" dataBefore="阿花"></div>
<script>
var box=document.querySelector('.box');
box.setAttribute('dataBefore','謝謝你');//第二個值為‘’就是偽元素隱藏效果
</script>
</body>
</html>

2.覆寫原有樣式
這個方法能更改偽元素的值和樣式,缺點就是會造成部分css多余代碼,設定content:’ ’ 就可以實作偽元素隱藏效果,當然你也可以設定opacity=0或者display=none都行,看需求
(1)css優先級覆寫
為父元素添加一個新的class類名,后面類名的優先級會高于前面的,將前面的樣式覆寫
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 300px;height: 200px;border: 5px solid black;margin: 100px auto;
}
.box:before{
content: '阿花';color: red;font-size: 24px;
}
.skate:before{
/*提前寫在css樣式表里,js添加完skate類名后便會覆寫前面box的樣式*/
content: '謝謝你';color: blue;font-size: 24px;}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box=document.querySelector('.box');
box.classList.add('skate');//添加classname skate
</script>
</body>
</html>

(2)更改class類名覆寫
在css中寫好新類名的樣式,通過js修改類名,之前的樣式就會失效(可以看一下和上一個方法其實沒什么太大區別)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 300px;height: 200px;border: 5px solid black;margin: 100px auto;
}
.box:before{
content: '阿花';color: red;font-size: 24px;
}
.skate{
width: 300px;height: 200px;border: 5px solid black;margin: 100px auto;
}
.skate:before{
content: '謝謝你';color: blue;font-size: 24px;}
</style>
</head>
<body>
<div class="box"></div>
<script>
var box=document.querySelector('.box');
box.className='skate';//更改classname為skate
</script>
</body>
</html>

(3)行內樣式表覆寫
這個適用的前提是你的css寫在了外部樣式表中,用js動態添加一個行內樣式,行內樣式優先級大于外部樣式,外部樣式就會失效;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="box"></div>
<script>
var style=document.createElement('style');//創建一個<style>標簽
var change=document.createTextNode('.box:before{content:"謝謝你";color:blue;}')//更改后偽元素的樣式
style.appendChild(change);//把樣式添加到style標簽里
document.body.appendChild(style);//把行內樣式表添加到html中
</script>
</body>
</html>
js執行的結果就相當于在head頭部前面添加了一個style的行內樣式表


轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/259484.html
標籤:其他
上一篇:jquery,關于回傳值呼叫問題
下一篇:vue02--文本渲染
