如何使用 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/