2012-08-05 101 views
0

我創建了一個簡單的jQuery圖像轉換查看器,並且每次加載新照片時,窗口自動滾動到剛加載的新圖像的頂部。我試圖阻止這一點,以便過渡不會中斷用戶在頁面上的任何位置。jquery禁用自動窗口滾動

這是到目前爲止我的代碼:

$(document).ready(function() { 

var slideShow = function() 
{ 
current_img = $("#current_img"); // <img> element with src to be changed 
height_width = 'width="100%" height="100%"'; 
photos = new Array('images/home_s1.png','images/home_s2.png', 'images/home_s3.png'); 
setTimeout(function() { current_img.fadeOut('fast', function() { current_img.attr('src', photos[0]); current_img.fadeIn('slow'); }); }, 0); 
setTimeout(function() { current_img.fadeOut('fast', function() { current_img.attr('src', photos[1]); current_img.fadeIn('slow'); }); }, 5000); 
setTimeout(function() { current_img.fadeOut('fast', function() { current_img.attr('src', photos[2]); current_img.fadeIn('slow'); }); }, 10000); 
setTimeout(function() { slideShow(); }, 15000); 
} 

$("img").ready(slideShow); 

}); 

我試圖操縱的preventDefault()函數的多種不同的方式,而且我自己也嘗試加載圖像(即加載到HTML的不同變化( )而不是img.attr('src')),但沒有運氣...任何有關實現此目的的最有效方式的建議?

+0

你有沒有發現這個答案嗎? http://stackoverflow.com/questions/1391833/how-to-prevent-window-from-scrolling-up-on-jquery-slidetoggle?rq=1 所有最好 – devanand 2012-08-05 09:21:43

回答

1

您似乎遇到的問題是默認實現.fadeIn().fadeOut()display屬性設置爲none。這會使元素的高度和寬度都爲0,這會導致一種跳躍效果。

您應該使用類似.fadeTo()的東西,並且在切換圖像時不要將不透明度一直設置爲0。類似於0.01的值也足夠,並且不會使jQuery將display屬性更改爲none

這裏有您需要setTimeout回調裏面做什麼的例子:

setTimeout(function() { 
    current_img.fadeTo('fast', 0.01, function() { 
     current_img.attr('src', photos[0]); 
     current_img.fadeTo('slow', 1); 
    }); 
}); 
+0

工作非常好聽!我之前沒有使用fadeTo函數。謝謝! – 2012-08-05 09:42:25

+0

@deraad歡迎您:) - P.S.,如果問題解決了,您應該將此答案標記爲已接受。 – 2012-08-05 09:51:40