如何在mouseenter上为使用css class悬停的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;
}
答案 0 :(得分:3)
实际上你不需要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>
答案 1 :(得分:0)
如果您只想使用CSS,请按以下代码
function myFunction() {
var btn = document.createElement('div');
btn.classList.add('test');
document.body.appendChild(btn);
}
&#13;
.customBackgroundForTouch:hover{
background-color:#F5F5DC;
}
&#13;
使用Jquery
<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>
&#13;
$(".customBackgroundForTouch").on("mouseenter", function(){
$(this).css({"background-color": "#F5F5DC"});
})
$(".customBackgroundForTouch").on("mouseleave", function(){
$(this).css({"background-color": "inherit"});
})
&#13;
.customBackgroundForTouch{
background-color:inherit;
}
&#13;