JQuery Fancybox打开延迟

JQuery Fancybox open delay

本文关键字:延迟 Fancybox JQuery      更新时间:2023-09-26

我有一个用于显示照片和描述的花哨盒子。现在它在mouseenter事件上打开fanybox。这段代码可以完美地工作:

$('.fancy_link').live('mouseenter', mouseEnter);
function mouseEnter()
{
jQuery(this).fancybox().trigger('click');
return false;
}

但是我需要设置打开fancybox的延迟时间。工作原理:用户将光标移动到链接上,1秒后,fancybox应该打开并显示内容。

如果用户在等待1秒之前将鼠标移开,则fancybox不应打开。

我尝试过JQuery delay()和setTimeout(),但它们都不能正常工作。1秒的延迟被两个方法忽略

使用setTimeout/clearTimeout…

//binding code...
$('.fancy_link').on('mouseenter',mouseEnter);
$('.fancy_link').on('mouseleave', mouseLeave);
//run when the mouse hovers over the item
function mouseEnter() {
  //clear any previous timer
  clearTimeout($(this).data('h_hover'));
  //get a reference to the current item, for the setTimeout callback
  var that = this;
  //set a timer, and save the reference to g_hover
  var h_hover = setTimeout(function(){
    //timer timed out - click the item being hovered
    $(that).click();
  }, 1000);
  //save the reference - attached to the item - for clearing
  //  data is a generic "store", it isn't saved to the tag in the dom.
  //  note: if you have a data-* attribute it is readable via data()
  $(this).data('h_hover',h_hover)
}
//handler for when the mouse leaves the item
function mouseLeave() {
  //clear the previously set timeout
  clearTimeout($(this).data('h_hover'));
}

这个可以帮到你

function openFancybox() {
    setTimeout( function() {$('#fancy_link').trigger('click'); },1000);
}

我想你将需要使用setTimeout和clearTimeout

下面的内容:

var timer;
$('.fancy_link').mouseenter(function(){
    var $this = $(this);
    timer = setTimeout(function(){
        $this.fancybox().trigger('click');
    }, 1000);
}).mouseleave(function(){
    clearTimeout(timer);
});

试试这个解决方案:

var timer = null;
$('.fancy_link').on('mouseenter', function() {
    timer = setTimeout(mouseEnter, 1000);
});
// clear timer when mouse leaves
$('.fancy_link').on('mouseleave', function() {
    clearTimeout(timer);
});