如何使用jQuery启用/禁用:hover?

3

我有一个像这样的 div

$("div").on("click", function(){

  $("div").css({"background-color":"#f1f1f1"});
  $("div").text('Sending ... (I want diactivate :hover)');
  setTimeout(function(){
    $("div").text('Click (I want activate :hover again)');
    $("div").hover(function(e) {
        $(this).css("background-color","#ddd8")
    });
  }, 5000);
  
});
div{
 padding: 20px;
  border: 1px solid #999;
  text-align: center;
  background-color: #f1f1f1;
  cursor: pointer;
}

div:hover{
  background-color: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click (I want activate :hover)</div>

我希望当用户点击那个 div 时,:hover 将被禁用,并在5秒后重新启用。但是我的代码只是停用了它。如何使其重新激活?


你需要执行 $(this).removeAttr('style') 并移除内联样式,这样它就不会再覆盖样式表了。但是所有这些都是一个非常糟糕的想法,也不是你应该采取的方式。 - adeneo
1个回答

2

给元素添加一个类,然后删除并添加该类来实现操作。

$("div").on("click", function() {

  $(this).toggleClass('bg hover')
         .text('Sending ... (I want diactivate :hover)');

  setTimeout(function() {
    $(this).toggleClass('bg hover')
           .text('Click (I want activate :hover again)');
  }.bind(this), 1000);

});
div {
  padding: 20px;
  border: 1px solid #999;
  text-align: center;
  background-color: #f1f1f1;
  cursor: pointer;
}
div.bg {
  background: red;
}
div.hover:hover {
  background-color: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hover">Click (I want activate :hover)</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接