简体   繁体   English

如何为鼠标悬停功能添加延迟?

[英]How do I add a delay to the mouseover function?

I'm making a calendar app using the jQuery plugin FullCalendar and I made a tab to the left of the calendar with the weeks from 1-6 on it. 我正在使用jQuery插件FullCalendar创建日历应用程序,并且在日历左侧创建了一个标签,其中包含1-6周。 When the user drags their mouse over one of the weeks the calendar switches to the view of the respective view. 当用户将鼠标拖到一周的某一周时,日历将切换到相应视图的视图。 This works but it can be annoying for the user if they do it accidentally. 这可以工作,但是如果用户不小心这样做可能会很烦人。 So, I want to add a delay to the function so that it will only happen if the user has their mouse on it for a few hundred milliseconds so it will happen less without the user wanting it to happen. 因此,我想为该功能添加一个延迟,以便仅在用户将鼠标放在其上数百毫秒的情况下才会发生此延迟,因此在用户不希望发生的情况下发生的延迟会更少。

$('#week3').mouseover(function() {
    $('#week3').css('color', 'white');
    $('#week3').css('background-color', '#6B8BA9');
    $('#week3').week3();

I want to add a short delay before $('#week3').css('color', 'white'); 我想在$('#week3').css('color', 'white');前添加一小段延迟$('#week3').css('color', 'white');

Use a timeout : 使用超时:

$('#week3').on({
    mouseenter: function() {
        var that = this;

        $(that).data('timer', 
            setTimeout(function() {
                $(that).css('color', 'white');
            },1000)
        ).css('background-color', '#6B8BA9').week3();
    },
    mouseleave: function() {
        clearTimeout( $(this).data('timer') );
    }
});

If I am understanding you correctly, then you will need a more complete solution like below 如果我对您的理解正确,那么您将需要一个更完整的解决方案,如下所示

var mouse_monitor

$('#week3').mouseover(function() {
  mouse_monitor = setTimeout(function(){
    $('#week3').css('color', 'white');
    $('#week3').css('background-color', '#6B8BA9');
    $('#week3').week3();
  }, 1500)
}); 

$('#week3').mouseout(function() { clearTimeout( mouse_monitor ); }

The var mouse_monitor is a global reference to your timeout function. var mouse_monitor是对您的超时功能的全局引用。 The mouseout function is missing in other post, which assures that your mouseover function will not fire if the user moves the mouse off the hover target before the value of the setTimeout expires. mouseout函数在其他文章中缺失,这确保了如果用户在setTimeout值到期之前将鼠标移离悬停目标,则不会触发mouseover函数。 Other examples will still invoke your mouseover function everytime, but with just an added delay, so they won't work for what I think you are trying to achieve. 其他示例仍然会每次都调用mouseover函数,但是会增加延迟,因此它们对我认为您要实现的目标无效。

您正在寻找setTimeout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM