gpt4 book ai didi

javascript - 更改文本背景荧光笔

转载 作者:行者123 更新时间:2023-11-28 00:41:47 24 4
gpt4 key购买 nike

所以我试图让我的 id="highlighter2" 的每一行的背景颜色 在被点击时有一个黄色背景所以它看起来类似于这个enter image description here

当它被点击时,该按钮被替换为“Unhighlight them all” 按钮,该按钮取消突出显示所有内容。我尝试使用 ID 定义 onclick,但改为更改背景,正确的做法/方法是什么?

代码:

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 -->

最佳答案

Paragraphs: the P element

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

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

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

要单独设置所有 p 元素的 backgroundColor,您必须首先定位所有元素。您可以使用 querySelectorAll() 来做到这一点.然后使用 forEach()NodeList 上像下面这样:

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 -->

关于javascript - 更改文本背景荧光笔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com