如何在关闭fancybox时停止页面重定向?

时间:2015-07-03 14:55:11

标签: javascript jquery html fancybox

我有以下代码

<script type="text/javascript">
        jQuery(document).ready(function() {
            beginCartnotification();
        });
        setTimeout(function () {
            window.location.href = "http://www.someurl.com";
        }, 5000);
    </script>


<script type="text/javascript">
        jQuery.fancybox({
            'width': '300',
            'height': '90',
            'padding': '40px',
            'autoDimensions': false,
            'border': '1px solid #005195',
            'autoScale': false,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'showCloseButton': true,
            'type': 'inline',
            'href': '#cartnotification-popup',
            'onClosed': function(){ //perform some task on closing the fancybox.}
        });
    }
</script>

现在我要做的是,如果用户点击花式框上的关闭按钮,页面不应该重定向。

如果用户在5秒后没有点击关闭按钮,则应将用户重定向到另一个页面。

如何实现内部 onClosed 功能?

http://fancybox.net/api

1 个答案:

答案 0 :(得分:2)

只需将setTimout添加到 fancybox onComplete属性,一旦显示内容,就会调用该属性。如果在关闭 fancybox 之前达到超时,请执行重定向。

onClose属性函数中清除超时,以确保不会触发window.loaction更改。

还要将fancybox设置添加到jQuery的.ready()方法,以确保在文档准备好后立即进行初始化。

<script type="text/javascript">
jQuery(document).ready(function() {

  beginCartnotification();

  // ADD A VAR TO HOLD YOUR TIMER.
  var timer;

  jQuery.fancybox({
    'width': '300',
    'height': '90',
    'padding': '40px',
    'autoDimensions': false,
    'border': '1px solid #005195',
    'autoScale': false,
    'transitionIn': 'fade',
    'transitionOut': 'fade',
    'showCloseButton': true,
    'type': 'inline',
    'href': '#cartnotification-popup',
    'onComplete': function() {
      timer = setTimeout(function () {
        // REDIRECTING TAKES PLACE AFTER 5 SEC.
        window.location.href = "http://www.someurl.com";
      }, 5000);
    },
    'onClosed': function() {
      // CLEAR THE TIMEOUT !!!
      clearTimeout(timer);
    }
  });

});
</script>