gpt4 book ai didi

javascript - 使用javascript突出显示文本不起作用

转载 作者:行者123 更新时间:2023-11-30 20:58:59 25 4
gpt4 key购买 nike

我想突出显示或将所有 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/

希望这对您有所帮助。

关于javascript - 使用javascript突出显示文本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47318166/

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