在 JavaScript 中动态设置某些标签的样式

例如,要设置正文的样式,您可以简单地执行document.body.style.color = "white"此操作,但如果我想使用 -tag 执行相同的操作,pre我该怎么做?



喵喔喔
浏览 79回答 3
3回答

Smart猫小萌

最好的解决方案是通过类来改变样式。这通常就是主题的工作方式。你在身体上设置了一个类来改变你想要改变的东西。window.setTimeout( function () {&nbsp; document.body.classList.add("luckyGreen")}, 4000)window.setTimeout( function () {&nbsp; document.body.classList.remove("luckyGreen")}, 8000)pre {&nbsp; background-color: #CCC;}body.luckyGreen {&nbsp; color:green;}body.luckyGreen pre {&nbsp; background-color: #CFC;}<pre>&nbsp;Hello there</pre>X<pre>&nbsp;Hello there</pre>Y<pre>&nbsp;Hello there</pre>但由于某种原因你想改变一个类,你可以编写一个新的 css 规则。function addRule() {&nbsp; var styleEl = document.createElement('style');&nbsp; document.head.appendChild(styleEl);&nbsp; var styleSheet = styleEl.sheet;&nbsp; var ruleStr = "pre { background-color: red; }"&nbsp; styleSheet.insertRule(ruleStr, styleSheet.cssRules.length);}window.setTimeout(addRule, 4000)<pre>&nbsp;Hello there</pre>X<pre>&nbsp;Hello there</pre>Y<pre>&nbsp;Hello there</pre>

GCT1015

在这种情况下,您需要使用getElementsByTagName如下:var tags = document.getElementsByTagName("pre");for(var i = 0; i < tags.length; i++)&nbsp; &nbsp; &nbsp;tags[i].style.color = "white";

江户川乱折腾

您可以在 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++) {&nbsp; preAll[i].style.backgroundColor = "#ddddff";}pre.one {&nbsp; color: red;&nbsp; font-weight: bold;}pre.two {&nbsp; color: blue;&nbsp; font-weight: 2;}pre.three {&nbsp; background-color: #ddffdd;}pre.four {&nbsp; color: green;&nbsp; background-color:#ffddff;&nbsp; font-weight: bold;}<div class="container">&nbsp; <pre>pretty pre</pre>&nbsp; <pre>pretty pre</pre>&nbsp; <pre>pretty pre</pre>&nbsp; <pre>pretty pre</pre></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5