在调整大小时启用/禁用jquery调用

时间:2012-08-16 02:33:43

标签: jquery

我正在构建一个响应式网站,因此需要不同的功能,具体取决于窗口的大小。

因此,如果屏幕宽度小于964px,我想禁用我的jquery调用。如果它超过964px,我想启用相同的调用。

这就是我得到的: http://jsfiddle.net/frogfacehead/2Mdem/1/

问题是,禁用部分不起作用。一旦启用,即使屏幕低于964px,它也不会禁用。

有什么想法吗?

3 个答案:

答案 0 :(得分:3)

当屏幕尺寸大于964px时,您将动画绑定到.test元素,以便取消绑定,您需要这样做

else {
        $body.html('Viewport is ' + mywidth + 'px wide. <span class="disable">[Disable Animation]</span>');
        $(".test").unbind("hover");
    }

答案 1 :(得分:2)

当页面大小发生变化时,为什么不在这些回调函数中检查页面的大小,而不是使用所有这些资源将悬停函数附加到该元素?

$(".test").hover(function() {
            if (width > 964) {
                $(this).animate({
                    width: "100px"
                })
            }
        }, etc.

问题是您添加了一个函数来处理悬停事件,但该函数永远不会被删除。随着页面宽度的变化,您会反复添加它。只需添加一次,然后检查该函数的处理程序中应该发生什么。作为正常工作的奖励,它应该更有效率。

答案 2 :(得分:1)

第一个问题是你正在根据你的resize事件绑定加载一个悬停/动画绑定到.test的队列。

您的实现可以改进(见下文),但如果您想在调整大小完成时触发函数调用,请考虑以下事项。

var resizeTimeout;
$win.resize(function() {
  clearTimeout(resizeTimeout);
  // handle normal resize as needed
  resizeTimeout = setTimeout(function() {
    // handle after finished resize
    checkwidth($win.width());
  }, 250); // delay by quarter second
});

您可以考虑这种方法:

// pull hover binding out, setup once to prevent building up queue
$(".test").hover(function() {
  if( $(".test").data('annimate') ){
    $(this).animate({
      width: "100px"
    });
  }
}, function() {
  if( $(".test").data('annimate') ){
    $(this).animate({
      width: "50px"
    });
  }
});

function checkwidth(mywidth) {
  if (mywidth > 964) {
    $body.html('Viewport is <strong>' + mywidth + 'px</strong> wide. <span class="enable">[Enable Animation]</span>');
    // set flag to allow annimation
    $(".test").data('annimate', true);
  } else {
    $body.html('Viewport is ' + mywidth + 'px wide. <span class="disable">[Disable Animation]</span>');
    // set flag to prevent annimation
    $(".test").data('annimate', false);
  }
}
相关问题