Javascript 禁用:悬停点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30118246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:41:36 来源:igfitidea点击:
Disable :hover on click
提问by frosty
I have a divthat has hover:
我有一个div悬停:
.div {
// css
}
.div:hover {
// css
}
But I want to disable the hover when you click on the div.
但是我想在您单击div.
回答by SW4
Option 1. The Javascript solution
选项 1. Javascript 解决方案
Simply add a class prohibiting the application of hover styling on click:
只需添加一个类,禁止在单击时应用悬停样式:
$('div').on('click', function() { // when you click the div
$(this).addClass('no-hover'); // add the class 'no-hover'
});
div {
color: blue;
}
div:not(.no-hover):hover { /* only apply hover styling when the div does not have the class 'no-hover' */
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hover!</div>
Option 2. The CSS solution
选项 2. CSS 解决方案
Alternatively, in pure CSS (although without rule persistence)
或者,在纯 CSS 中(尽管没有规则持久性)
div {
color: blue;
}
div:not(:focus):hover {
color: red;
}
div:focus {
outline: none;
}
<div tabindex="0">hover!</div>
回答by Rafet
All you need is this:
你只需要这个:
$('[your selector]').css({'pointer-events': 'none'})
回答by Hector
.disabled {
opacity: 0.5;
pointer-events: none;
}
.disabled:hover *
pointer-events: none;
cursor: not-allowed;
}
回答by Rahul Tripathi
Try like this:
像这样尝试:
$('#myid').on({
mouseover: function(){
$(this).css({background: '#F94'});
},
mouseleave: function(){
$(this).css({background: '#DDD'});
},
click: function(){
$(this).off('mouseleave');
}
});
回答by Luís P. A.
Try this:
尝试这个:
JQUERY
查询
$(function() { //run when the DOM is ready
$(".div").click(function() { //use a class, since your ID gets mangled
$(this).addClass("active"); //add the class to the clicked element
});
});
CSS
CSS
.div.active:hover {
cursor:default;
//same CSS as the DIV
}

