gpt4 book ai didi

javascript - 如何更改 HTML 鼠标输入的背景颜色

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

如何使用 css 类更改 mouseenter 上悬停的 HTML 元素的背景颜色。相同的 css 类已添加到多个 HTML 元素。当鼠标悬停在 html 元素上时,它会更改所有添加了相同 css 类的 HTML 元素的背景颜色。

注意:我不能添加#id

HTML:

<div class="customBackgroundForTouch">
<p > Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

<div class="customBackgroundForTouch">
<p > Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

JQuery:

<script>        
$(".customBackgroundForTouch").addEventListener("mouseenter", function(){
$(".customBackgroundForTouch").css({"background-color": "#F5F5DC"});
});

$(".customBackgroundForTouch").addEventListener("mouseleave", function(){
$(".customBackgroundForTouch").css({"background-color": "inherit"});
});
</script>

CSS:

.customBackgroundForTouch{
background-color:inherit;
}

最佳答案

其实你不需要jQuery来解决它。你甚至不需要 JavaScript...

只有css解决方案:

.customBackgroundForTouch:hover {
background-color: #F5F5DC;
}
<div class="customBackgroundForTouch">
<p> Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

<div class="customBackgroundForTouch">
<p> Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

纯 JS 解决方案:

var cls = document.getElementsByClassName('customBackgroundForTouch');
Array.from(cls).forEach(function(v) {
v.addEventListener("mouseenter", function() {
this.style.background = "#F5F5DC";
});
v.addEventListener("mouseleave", function() {
this.style.background = "inherit";
});
});
.customBackgroundForTouch {
background-color: inherit;
}
<div class="customBackgroundForTouch">
<p> Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

<div class="customBackgroundForTouch">
<p> Welcome to Javatpoint.com, Here you get tutorials on latest technologies.</p>
<p>This is second paragraph</p>
</div>

关于javascript - 如何更改 HTML 鼠标输入的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42719081/

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