我有这个 HTML:
<html>
<head>
<title>Mouseenter and Click combined</title>
</head>
<body>
<a id="linkselector" href="#">Click here</a>
</body>
</html>
这是我的 jQuery 代码:
jQuery( document ).ready( function($) {
//This is the click event
$('#linkselector').live('click',(function() {
alert('You are clicked!');
}));
//This is the mouseover event
$('#linkselector').live('mouseenter', (function(evt){
$('<div class="popupx"></div>').appendTo(document.body);
$('.popupx').html('<img src="http://' + $(this).data('id') + '.jpg.to/">');
$('.popupx').css({left: evt.pageX+30, top: evt.pageY-15}).show();
$('.popupx').css('border','0');
$(this).live('mouseleave', (function(){
$('.popupx').hide();
}));
}));
});
最后是我的 CSS:
.popupx{
position:absolute;
width:30px;
height:30px;
}
.popupx img{
width:30px;
height:30px;
}
当我将链接悬停时,图像会正确显示,因此可以正常工作。问题是当我点击它时,它不再触发点击事件。但是,如果我删除 mouseenter/hover 机制。点击事件工作正常。
当用户将鼠标悬停在链接上时,如何触发 click 事件?可能我错过了代码中的一些重要内容。感谢您的任何提示。
更新:我已经成功地将三个事件组合在一个函数中,但我仍在使用 LIVE 和 IF/else,因为由于某种原因 ON 不起作用。无论如何,我让 mouseenter 和 mouseleave 在下面的逻辑中正常工作。但是当 mouseenter 被激活时单击仍然不起作用。可能我需要找到一种在仍然显示悬停或 mouseenter 事件时触发 click 事件的方法。
$('#linkselector').live('click mouseleave mouseenter',(function(evt) {
if (evt.type === 'click') {
//This is a click event
//This won't fire when the mouseenter or hover is shown
} else if (evt.type === 'mouseenter') {
//This is working nicely
$('<div class="popupx"></div>').appendTo(document.body);
$('.popupx').html('<img src="/image.png">');
$('.popupx').css({left: evt.pageX-60, top: evt.pageY-60}).show();
$('.popupx').css('border','0');
} else if (evt.type === 'mouseleave') {
//This is also working nicely
$('.popupx').remove();
}
}));