我有一个隐藏的 div,我只想在用户将鼠标悬停在另一个触发元素上几秒钟时显示隐藏的 div,而不是在用户将鼠标悬停在触发元素上时显示隐藏的 div
这是我的javascript代码
$('.c_like_icon').mouseover(
function() {
var timeout = setTimeout(function(){
var comment_id=$(this).attr('data-commentId');
$.ajax({
url: 'ajax_c_like_user.php',
method:'post',
data:{comment_id:comment_id},
success:function(data){
var like_num=$('#'+comment_id+'c_like_number').text();
if(like_num>=1){
$('#'+comment_id+'like_user_w').html(data);
$('#'+comment_id+'like_user_w').show();
}
else{
$('#'+comment_id+'like_user_w').hide();
}
}
})
}, 2000); //2 seconds
},
function(){
var comment_id=$(this).attr('data-commentId');
clearTimeout(timeout); //cancel the timeout if they hover off
$('#'+comment_id+'like_user_w').hide();
// do stuff when hover off
}
)
最佳答案
在 hover in 函数中定义超时并在 hover out 函数中清除,以防止在时间用完之前离开时被触发,如下所示:
var timeout;
$('#trigger').hover(
function() {
timeout = setTimeout(function(){
// do stuff on hover
$('#hiddenDiv').show();
}, 2000); //2 seconds
},
function(){
clearTimeout(timeout); //cancel the timeout if they hover off
// do stuff when hover off
$('#hiddenDiv').hide();
}
);
关于javascript - 仅当用户将元素悬停几秒钟时才显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21949343/