如何在鼠标输入上更改 HTML 的背景颜色

重力加速度

如何为使用 css 类悬停的 HTML 元素更改 mouseenter 上的背景颜色。已将相同的 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>  

查询:

<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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章