我想将所有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";
}
答案 0 :(得分:1)
您可以使用querySelector
和querySelectorAll
。
我附上了一个JSFiddle来看两个选项 - 一个遍历段落
var paragraph = document.querySelectorAll("p");
paragraph.forEach(p => {
p.style.color ="yellow";
});
并且第二个选项只是向父(#poem)添加一个css类,显然是首选方式。
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/
希望这有帮助。
答案 1 :(得分:0)
这应该有效
<script type="text/javascript">
document.getElementById('some_id').onclick= function() {
var p = this.parentNode.style;
p.color = yellow;
};
</script>
编辑:切换按钮
<script type="text/javascript">
document.getElementById('some_id').onclick= function() {
var p = this.parentNode.style;
if (p.color = yellow) p.color = white;
else p.color = yellow;
};
</script>
答案 2 :(得分:0)
试试这个:
document.getElementById("yellow").addEventListener("click", myFunction);
function myFunction() {
var x = document.getElementById("poem");
if (x.style.color == "blue") {
x.style.color == "yellow";
} else if (x.style.color == "yellow") {
x.style.color == "blue";
}
}