javascript - 仅当用户将元素悬停几秒钟时才显示 div

标签 javascript jquery html css

我有一个隐藏的 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/

相关文章:

javascript - 如何识别jquery中保存的浏览器用户名和密码

asp.net - 如何获取服务器端var值?

php - 我想将图像和文字包裹在杯子、T 恤、 Crystal 等产品周围

html - 这在 CSS 中正常吗?

jquery - 在某个 div 处停止滚动

javascript - 用户界面.路由器 : Save $state state when leaving and continous when reentering

jquery - 如何找到被点击元素的id

php - 如何将数组插入到jquery的隐藏输入中

javascript - .each() 函数,每次迭代之间有间隔

html - flex : Aligning align a button to the right and content to the left