2

我正在构建一个响应式站点,因此根据窗口的大小需要不同的功能。

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

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

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

有任何想法吗?

4

3 回答 3

3

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

else {
        $body.html('Viewport is ' + mywidth + 'px wide. <span class="disable">[Disable Animation]</span>');
        $(".test").unbind("hover");
    }
于 2012-08-16T02:51:58.417 回答
2

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

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

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

于 2012-08-16T02:52:21.997 回答
1

第一个问题是您正在加载.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);
  }
}
于 2012-08-16T03:22:46.533 回答