最新文章專題視頻專題問答1問答10問答100問答1000問答2000關鍵字專題1關鍵字專題50關鍵字專題500關鍵字專題1500TAG最新視頻文章視頻文章20視頻文章30視頻文章40視頻文章50視頻文章60 視頻文章70視頻文章80視頻文章90視頻文章100視頻文章120視頻文章140 視頻2關鍵字專題關鍵字專題tag2tag3文章專題文章專題2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章專題3
當前位置: 首頁 - 科技 - 知識百科 - 正文

如何用JavaScript修改偽類樣式

來源:懂視網 責編:小采 時間:2020-11-27 20:10:57
文檔

如何用JavaScript修改偽類樣式

如何用JavaScript修改偽類樣式:我們都聽說過css偽類但是并沒有聽說過JavaScript也有偽類,項目中時常會需要用到使用JavaScript來動態控制偽元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結一下幾種常見的方法。HTML<p class=
推薦度:
導讀如何用JavaScript修改偽類樣式:我們都聽說過css偽類但是并沒有聽說過JavaScript也有偽類,項目中時常會需要用到使用JavaScript來動態控制偽元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結一下幾種常見的方法。HTML<p class=

我們都聽說過css偽類但是并沒有聽說過JavaScript也有偽類,項目中時常會需要用到使用JavaScript來動態控制偽元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結一下幾種常見的方法。

HTML

<p class="red">Hi, this is a plain-old, sad-looking paragraph 
tag.</p>
CSS
.red::before {
content: 'red';
color: red;
}

方法一

使用JavaScript或者jQuery切換<p>元素的類名,修改樣式。

.green::before {
content: 'green';
color: green;
}
$('p').removeClass('red').addClass('green');

方法二

在已存在的<style>中動態插入新樣式。

document.styleSheets[0].addRule('.red::before','color: green');
document.styleSheets[0].insertRule('.red::before { color: green }', 0);

方法三

創建一份新的樣式表,并使用JavaScript或jQuery將其插入到<head>中

// Create a new style tag
var style = document.createElement("style");
// Append the style tag to head
document.head.appendChild(style);
// Grab the stylesheet object
sheet = style.sheet
// Use addRule or insertRule to inject styles
sheet.addRule('.red::before','color: green');
sheet.insertRule('.red::before { color: green }', 0);

jQuery

$('<style>.red::before{color:green}</style>').appendTo('head');

方法四

使用HTML5的data-屬性,在屬性中使用attr()動態修改。

<p class="red" data-attr="red">Hi, this is plain-old, sad-looking paragraph tag.</p>
.red::before {
content: attr(data-attr);
color: red;
}
$('.red').attr('data-attr', 'green');

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com

文檔

如何用JavaScript修改偽類樣式

如何用JavaScript修改偽類樣式:我們都聽說過css偽類但是并沒有聽說過JavaScript也有偽類,項目中時常會需要用到使用JavaScript來動態控制偽元素(:before,:after)的樣式,但是我們都知道JavaScript或jQuery并沒有偽類選擇器。這里總結一下幾種常見的方法。HTML<p class=
推薦度:
標簽: 修改 改變 js
  • 熱門焦點

最新推薦

猜你喜歡

熱門推薦

專題
Top
国产精品久久久久精品…-国产精品可乐视频最新-亚洲欧美重口味在线-欧美va免费在线观看