2012-08-16 52 views

回答

2

而不是使用那些資源來把懸停函數作爲頁面大小的變化,爲什麼不檢查頁面的大小在這些回調函數?

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

問題是您添加一個函數來處理懸停事件,但該函數永遠不會被刪除。隨着頁面寬度的變化,您不斷添加它。只需添加一次,然後檢查該函數的處理函數中會發生什麼。作爲正確工作的獎勵,它應該更有效一些。

+0

優秀的建議。謝謝! – frog 2012-08-16 03:32:56

3

當屏幕的尺寸小於964px您的動畫結合。測試元件更大所以解除綁定,你需要做這樣的

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

注意,當你不給回調函數的引用調用解除綁定,這將解除綁定所有綁定到它。這可能是需要的,但值得指出。 – Brad 2012-08-16 02:54:25

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); 
    } 
}