【发布时间】:2011-12-22 01:19:30
【问题描述】:
$('.xx').mouseenter(function(){
if($(this).is(':hover'))
alert('d');
else
alert('f');
});
这是我的代码,它应该提醒 'd' 但每次它都会提醒 'f' 这里有什么错误
【问题讨论】:
标签: jquery if-statement hover
$('.xx').mouseenter(function(){
if($(this).is(':hover'))
alert('d');
else
alert('f');
});
这是我的代码,它应该提醒 'd' 但每次它都会提醒 'f' 这里有什么错误
【问题讨论】:
标签: jquery if-statement hover
function idIsHovered(id){
return $("#" + id + ":hover").length > 0;
}
【讨论】:
:hover 是 CSS pseudo-class,而不是 jQuery 选择器。它不能在所有浏览器上可靠地与is() 一起使用。
【讨论】:
正如 Frederic 所说,:hover 是 CSS 的一部分,而不是 jQuery 中的选择器。
有关替代解决方案,请阅读How do I check if the mouse is over an element in jQuery?
在 mouseout 上设置超时以淡出并将返回值存储到 对象中的数据。然后onmouseover,如果有则取消超时 数据中的价值。
删除淡出回调的数据。
【讨论】:
试试这样的-
$('.xx').hover(function(){
alert('d');
}, function() {
alert('f);
});
【讨论】:
x.filter(':hover').length
当您已经查询了一些对象/或内部回调函数时,这也可能是可用的。
【讨论】:
为什么不直接使用 .hover?
$(".xx").hover(function(){
alert("d");
});
【讨论】:
试试这样的
flag = ($('.xx:hover').length>0);
这样就可以判断鼠标是不是对象了
【讨论】:
这是一个小 jQuery 插件,用于检查鼠标是否在元素上。
用法:
$("#YourElement").isMouseOverMe();
示例:
(function($) {
var mx = 0;
var my = 0;
$(document).mousemove(function(e) { // no expensive logic here
mx = e.clientX;
my = e.clientY;
})
$.fn.isMouseOverMe = function() {
var $el = $(this);
var el_xmin = $el.offset().left;
var el_ymin = $el.offset().top;
var el_xmax = el_xmin + $el.width();
var el_ymax = el_ymin + $el.height();
return mx >= el_xmin && mx <= el_xmax && my >= el_ymin && my <= el_ymax;
};
}(jQuery));
$(document).mouseup(function(e) {
console.log($("#div").isMouseOverMe())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Click inside or outside of the yellow box</h2>
<div id="div" style="width:200px;height:200px;background-color:yellow;margin-top:50px"></div>
【讨论】: