亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 JavaScript 中動態設置某些標簽的樣式

在 JavaScript 中動態設置某些標簽的樣式

喵喔喔 2023-12-04 19:23:48
例如,要設置正文的樣式,您可以簡單地執行document.body.style.color = "white"此操作,但如果我想使用 -tag 執行相同的操作,pre我該怎么做?
查看完整描述

3 回答

?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

最好的解決方案是通過類來改變樣式。這通常就是主題的工作方式。你在身體上設置了一個類來改變你想要改變的東西。


window.setTimeout( function () {

  document.body.classList.add("luckyGreen")

}, 4000)


window.setTimeout( function () {

  document.body.classList.remove("luckyGreen")

}, 8000)

pre {

  background-color: #CCC;

}



body.luckyGreen {

  color:green;

}

body.luckyGreen pre {

  background-color: #CFC;

}

<pre>

 Hello there

</pre>

X

<pre>

 Hello there

</pre>

Y

<pre>

 Hello there

</pre>

但由于某種原因你想改變一個類,你可以編寫一個新的 css 規則。


function addRule() {

  var styleEl = document.createElement('style');

  document.head.appendChild(styleEl);

  var styleSheet = styleEl.sheet;

  var ruleStr = "pre { background-color: red; }"

  styleSheet.insertRule(ruleStr, styleSheet.cssRules.length);

}



window.setTimeout(addRule, 4000)

<pre>

 Hello there

</pre>

X

<pre>

 Hello there

</pre>

Y

<pre>

 Hello there

</pre>


查看完整回答
反對 回復 2023-12-04
?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

在這種情況下,您需要使用getElementsByTagName如下:


var tags = document.getElementsByTagName("pre");

for(var i = 0; i < tags.length; i++)

     tags[i].style.color = "white";


查看完整回答
反對 回復 2023-12-04
?
江戶川亂折騰

TA貢獻1851條經驗 獲得超5個贊

您可以在 CSS 中創建類,然后切換它們或添加/刪除它們或手動執行類似的操作。


let v3 = document.getElementsByTagName("pre")[2];

v3.classList.add('three');


let pre = document.getElementsByTagName("pre")[0];

pre.classList.add('one');


let preAll = document.getElementsByTagName("pre");

preAll[3].classList.add('four');


let i;

for (i = 0; i < preAll.length -1; i++) {

  preAll[i].style.backgroundColor = "#ddddff";

}

pre.one {

  color: red;

  font-weight: bold;

}


pre.two {

  color: blue;

  font-weight: 2;

}


pre.three {

  background-color: #ddffdd;

}


pre.four {

  color: green;

  background-color:#ffddff;

  font-weight: bold;

}

<div class="container">

  <pre>pretty pre</pre>

  <pre>pretty pre</pre>

  <pre>pretty pre</pre>

  <pre>pretty pre</pre>

</div>


查看完整回答
反對 回復 2023-12-04
  • 3 回答
  • 0 關注
  • 224 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號