因此,我试图让我的id="highlighter2"
的每行背景颜色 在单击时具有黄色背景,因此看起来与此类似/ p>
并在单击时将按钮替换为“全部取消突出显示” 按钮,从而取消突出显示所有内容。我尝试用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 -->
答案 0 :(得分:1)
P元素代表一个段落。它不能包含块级元素(包括P本身)。
因此,请使用其他元素来包装所有p
元素,例如div
。
您可以根据按钮的文本更改背景颜色和文本。
要分别设置所有backgroundColor
元素的p
,您必须首先定位所有元素。您可以使用querySelectorAll()
来做到这一点。然后按照以下方式在 NodeList 上使用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 -->
答案 1 :(得分:0)
document.body.style.backgroundColor
将您的风格应用于身体。试试这个document.getElementById("highlighter2").style.backgroundColor
或document.p.style.backgroundColor