簡體   English   中英

JQuery:我的'滾動'事件很慢。我究竟做錯了什么?

[英]JQuery: My 'scroll' event is CRAZY slow. What am I doing wrong?

我有4個DIV ,當你滾動其中一個div時,我想要觸發一個scroll事件。 這是下面的代碼。

$('#div1, #div2, #div3, #div4').scroll(function() {
    alert('...');
});

在Firefox / Chrome中,運行速度很快; 但是,在Internet Explorer中,它運行速度很慢,實際上阻止了我滾動div。

我正在使用最新版本的JQuery(v.1.4.1)。

問題 :運行上面的代碼有更有效的方法嗎? 如果是這樣,怎么樣?

更新 :自從被問及,我已經在我的整個代碼下面包含:

$('#div1, #div2, #div3, #div4').scroll(function() {
   /* find the closest (hlisting) home listing to the middle of the scrollwindow */ 
    var scrollElemPos = activeHomeDiv.offset();
    var newHighlightDiv = $(document.elementFromPoint(
        scrollElemPos.left + activeHomeDiv.width()  / 2,
        scrollElemPos.top  + activeHomeDiv.height() / 2)
    ).closest('.hlisting');
    if(newHighlightDiv.is(".HighlightRow")) return;
    $('.HighlightRow').removeClass("HighlightRow");
    newHighlightDiv.addClass('HighlightRow');

   /* change the map marker icon to denote the currently focused on home */
   var activeHomeID = newHighlightDiv.attr("id");
   if (activeHomeMarkerID) {
      // unset the old active house marker to a normal icon
      map.markers[activeHomeMarkerID].setIcon('http://example.com/images/house-icon.png');
   }
   activeHomeMarkerID = activeHomeID.substring(4); // set the new active marker id
   map.markers[activeHomeMarkerID].setIcon('http://example.com/images/house-icon-active.png');     
});

更新2:

所以我在下面和IE中實現了計時器選項,它仍然很慢。 還有其他想法嗎?

在IE中,滾動事件比在Firefox中更頻繁地調度。 您在事件處理程序中執行了許多DOM操作,這使得它運行得更慢。

當用戶停止或暫時停止滾動時,請考慮執行所有這些操作。 這是一篇關於如何實現這種技術的文章 - http://ajaxian.com/archives/delaying-javascript-execution

編輯 :這是一個實現

var timer = 0,
    delay = 50; //you can tweak this value
var handler = function() {
    timer = 0;
    //all the stuff in your current scroll function
}

$('#div1, #div2, #div3, #div4').scroll(function() {
    if (timer) {
        clearTimeout(timer);
        timer = 0;
    }
    timer = setTimeout(handler, delay);
});

編輯2 :你可以附加一個探查器(如IE8探查器),看看運行緩慢的是什么? 你的DOM有多復雜?

以下是一些提高代碼性能的建議:

  1. 你真的需要每次測量activeHomeDiv.offset()嗎? 你可以測量一次並將其存放在某個地方(如果位置沒有變化)嗎? 測量大小會導致瀏覽器重繪。
  2. newHighlightDiv.is(".HighlightRow")更改為newHighlightDiv.hasClass("HighlightRow")
  3. $('.HighlightRow').removeClass("HighlightRow") - 添加元素前綴並從id選擇器/元素引用下降,例如$('div.HighlightRow', '#ancestorDiv')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM