3

これらのdivの1つをスクロールしたときにDIV、イベントを発生させたい4つがあります。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ではそれはまだ同じくらい遅いです。他のアイデアはありますか?

4

1 に答える 1

6

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')ます。
于 2010-01-28T22:19:13.500 に答える