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

标签 javascript jquery html css sapui5

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

相关文章:

javascript - 无法定义数组元素

javascript - Angular2 数据在 IE11 中未绑定(bind)

javascript - 使用 jQuery Select2 多个未获取 html 选择选项

jQuery获取所选内容前后所有span的内容

javascript - 获取委托(delegate)选择器的索引

JavaScript 解构并分配给新对象

java - 从文件系统读取二进制文件作为 BLOB 以在 rhino 中使用 javascript

javascript - 如何将类添加到 onclick 元素之外的元素

javascript - 如何在没有中继器的情况下在表格中查找元素

javascript - 如果单击下一个按钮,如何验证我的表单