更改文本背景荧光笔

Changing Text background highlighter

所以我试图让我的 id="highlighter2" 的每一行 的背景颜色 在单击时具有黄色背景,因此它看起来类似于此

并且当它被点击时,该按钮被替换为 "Unhighlight them all" 按钮,这将取消突出显示所有内容。我试图用 id 定义 onclick 但改为更改背景,do/approach 这个的正确方法是什么?

代码:

function Highlighter() {
  var p = document.getElementById("poem"); // get the paragraph
  var p = document.getElementById("highlighter2");
  document.body.style.backgroundColor = "yellow";
}
#poem {
  padding: 10px;
  margin-bottom: 10px;
  color: blue;
  font-size: 1.25em;
  font-family: sans-serif;
  background-color: silver;
  border: 1px dashed black;
  width: 70%;
}
<div id="poem">
  <h2> How Many, How Much </h2>
  <h4> by Shel Silverstein </h4>

  <p id="highlighter2">
    <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>
  </p>


</div>

<button type="button" onclick="Highlighter()">Click to highlight</button>
<!-- Highlight -->

document.body.style.backgroundColor 会将您的样式应用到正文中。试试这个 document.getElementById("highlighter2").style.backgroundColor

document.p.style.backgroundColor

Paragraphs: the P element

The P element represents a paragraph. It cannot contain block-level elements (including P itself).

因此,使用一些其他元素来包裹所有 p 元素,例如 div

您可以根据按钮的文字更改背景颜色和文字。

要单独设置所有 p 元素的 backgroundColor,您必须首先定位所有元素。您可以通过在 NodeList 上使用 querySelectorAll(). Then use forEach() 来做到这一点,如下所示:

function Highlighter(btn) {
  var p = document.querySelectorAll('#highlighter2 > p'); // get the paragraph
  if(btn.textContent == 'Click to highlight'){
    p.forEach(function(pEl){
      pEl.style.backgroundColor = "yellow";
    }); 
    btn.textContent = 'Unhighlight them all';
  }
  else{
    p.forEach(function(pEl){
      pEl.style.backgroundColor = "";
    });
    btn.textContent = 'Click to highlight';
  }
}
#poem {
  padding: 10px;
  margin-bottom: 10px;
  color: blue;
  font-size: 1.25em;
  font-family: sans-serif;
  background-color: silver;
  border: 1px dashed black;
  width: 70%;
}
<div id="poem">
  <h2> How Many, How Much  </h2>
  <h4> by Shel Silverstein </h4>

  <div id="highlighter2">
    <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>


</div>

<button type="button" onclick="Highlighter(this)">Click to highlight</button><!-- Highlight -->