gpt4 book ai didi

javascript - 单击时如何更改文本的颜色

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:55 24 4
gpt4 key购买 nike

我希望能够更改文本的颜色,类中的“test”,单击它们时的“t1”。我希望它们都在仅单击一个时改变颜色。如您所见,它们被另一个 div 分隔,这只是因为这是我希望它们在我的页面上的顺序。

感谢您的帮助!

<script>

function change(div){
if (div.style.color == "rgb(252, 198, 162)")
{
div.style.color="rgb(220, 20, 60)";
}
else
{
div.style.color="rgb(252, 198, 162)";
}
}
</script>


<div class="t1" style="color: rgb(252,198,162);" onclick="change(this);">
<p>test</p>
</div>
<div class="t2" style="color: rgb(252, 198, 162);" onlcick="change(this);">
<p> test </p>
</div>
<div class="t1" style="color: rgb(252,198,162);" onclick="change(this);">
<p>test</p>
</div>

最佳答案

这是一个使用纯 javascript 的简单解决方案

function change(div) {

var clasNs = div.className; //get class name of the clicked element

var elements = document.querySelectorAll("." + clasNs); // get all element that has this class name
elements.forEach(myFunction) // for each element change color

}

function myFunction(item) {
if (item.style.color == "rgb(252, 198, 162)") {
item.style.color = "rgb(220, 20, 60)";
} else {
item.style.color = "rgb(252, 198, 162)";
}
}
<div class="t1" style="color: rgb(252,198,162);" onclick="change(this);">
<p>test</p>
</div>
<div class="t2" style="color: rgb(252, 198, 162);" onlcick = "change(this);">
<p> test </p>
</div>
<div class="t1" style="color: rgb(252,198,162);" onclick = "change(this);">
<p>test</p>
</div>

关于javascript - 单击时如何更改文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43704851/

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