2012-10-03 116 views
1

我有一個傳送帶,我需要根據瀏覽器的當前寬度重新定位傳送帶幻燈片。我需要遵循的規則是:在窗口上更改背景位置調整大小導致圖像閃爍

browserWidth > 1200: do not reposition slide 
browserWidth > 960 && browserWidth < 1200: move slide background X position based 
              on the formula (25/48*browserWidth)-625 
browserWidth < 960: reposition background X position to -125px 

我寫了一些JavaScript來做到這一點,但每當我調整瀏覽器的圖像開始閃爍了很多。我認爲計算機在嘗試重新渲染背景圖像時遇到了問題,因爲它們的分辨率很高。有沒有辦法解決這個閃爍的問題?

$(window).resize(function() { 
    var winW = $(window).width(); 
    if (winW > 960 && winW < 1200) { 
     $('#' + carouselID).css('left', '600px'); 
     var leftValue = ((25/48) * winW - 625) + 'px'; 
     var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
     $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
    } else if (winW <= 960) { 
     $('#' + carouselID).css('left', '600px'); 
     var leftValue = '-125px'; 
     var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
     $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
    } else if (winW >= 1200) { 
     $('#' + carouselID).css('left', '50%'); 
     var leftValue = 'left'; 
     var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
     $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
    } 
}); 

回答

1

我建議把尺寸調整代碼放在timeout之內。一些瀏覽器喜歡觸發多個大小調整事件,這可能是導致閃爍發生的原因。試試這樣的:

var timeout; 
$(window).resize(function() { 
    clearTimeout(timeout); 
    timeout = setTimeout(function() { 
     var winW = $(window).width(); 
     if (winW > 960 && winW < 1200) { 
      $('#' + carouselID).css('left', '600px'); 
      var leftValue = ((25/48) * winW - 625) + 'px'; 
      var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
      $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
     } else if (winW <= 960) { 
      $('#' + carouselID).css('left', '600px'); 
      var leftValue = '-125px'; 
      var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
      $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
     } else if (winW >= 1200) { 
      $('#' + carouselID).css('left', '50%'); 
      var leftValue = 'left'; 
      var backgroundAtr = 'url(http://www.placehold.it/1200x800) ' + leftValue + ' top no-repeat'; 
      $('#' + carouselID + ' .slides .slide').css('background', backgroundAtr); 
     } 
    }, 10); 
}); 

這將首先清除超時,如果有的話。然後它將設置您的調整大小代碼在10ms時間內執行。這應該讓瀏覽器有足夠的時間喘口氣,並停止發射多個調整大小事件 - 其基本上是一個反彈函數。

+0

謝謝。這正是我正在尋找的。這仍然有些滯後。是否有更多優化可以在我的代碼上執行? – Jon

+1

Nm。我只是修改了'background-position-x',而不是修改'background'屬性。 – Jon

相關問題