我想突出显示所有p元素的背景色或将其更改为黄色,但是不起作用。

我还希望我的按钮是一个突出显示和突出显示段落元素的开关。那可能吗?帮助将不胜感激!

 <html>
<head>
  <script type="text/javascript" src="task2.js"></script>
  <style>
  #poem {
    padding: 10px;
    margin-bottom: 10px;
    color: blue;
    font-size: 1.25em;
    font-family: sans-serif;
    background-color: silver;
    border: 1px dashed black;
    width: 30%;
  }
  </style>
</head>
<body>
<div id="poem">
<h2> How Many, How Much  </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>

<button id="yellow">Click to Highlight </button>
</body>
</html>


这是我的外部js文件

window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}

最佳答案

您可以使用querySelectorquerySelectorAll
我附加了一个JSFiddle来查看2个选项-一个遍历该段

var paragraph = document.querySelectorAll("p");
    paragraph.forEach(p => {
      p.style.color ="yellow";
    });


第二种选择只是将css类添加到父类(#poem),这显然是首选方法。

var poem = document.querySelector('#poem');
    poem.classList.add('yellow'); // and of course you need to define the `.yellow {color: yellow;}` in your css.


https://jsfiddle.net/L0dnbj0h/2/

希望这可以帮助。

09-10 05:15
查看更多