禁用单击div但不悬停?

时间:2018-06-01 00:49:03

标签: jquery css

我试图禁用点击div,但不会悬停。 我尝试使用css:pointer-events:none;,但它也会禁用悬停效果。

我也试过jquery,但没有成功。

有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:1)

只使用单行代码

$("#yourdivid").off('click');

试试这个例子

$(function () {
    $("#banner-message").click(function(){
    $(this).removeClass("alt");
  });
    $("#banner-message").off('click');//this line disable click event
    $("#banner-message").hover(function(){
         $(this).addClass("alt");
    });
    
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Disable Click Event and Enable for Hover</p>
</div>

答案 1 :(得分:0)

试试这个例子:

&#13;
&#13;
$(function () {
    $("#disabledDiv").off('click').on('mouseover mouseout', function(e){
    let $this = $(this);
         if(e.type === 'mouseover'){
         $this.css('background-color', 'red');
         }else if(e.type === 'mouseout'){
         $this.css('background-color', 'green');
         } 
    });
    
});
&#13;
#disabledDiv
{
background-color:green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="disabledDiv">
  Hover Me
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我认为这就是你要找的东西:

这是我的虚拟HTML:

<span>
<div id="disableButton">
Hover me. OR. Click me.
</div>
</span>

这是我的jquery:

$("#disableButton").click(function(){
  $(this).attr("disabled", "disabled");
});
$("#disableButton").mouseleave(function(){
    $(this).removeAttr("disabled");
});

这是我用过的css,可以帮助您正确理解其功能:

#disableButton:hover{
  background-color: yellow;
}

div#disableButton[disabled=disabled]{
  background-color:grey;
}

这是我小提琴的链接:https://jsfiddle.net/x5ve63w5/3/

我希望这会有所帮助。

感谢。

相关问题