2014-07-24 24 views
0

我試圖根據窗口的滾動位置更改靜態定位圖像的來源。用滾動更改靜態定位圖像

基本上,我想循環通過MRI掃描圖像,取決於視口相對於頁面的位置。我想在頁面的長度上打通所有100多張圖片。這個長度會改變,所以我試圖找出如何使它成比例。

我承認,我是新來的編碼,因此它可能是最好使用僞代碼,而不是試圖代碼:

window.image1position == (1/[#images]) * document.totalheight 
window.image2position == (2/[#images]) * document.totalheight 
... 

if window.scrollposition == window.image1position 

    set image.src = image1.png 

elseif window.scrollposition == window.image2position 

    set image.src = image2.png 
... 

會有人能夠幫助我這樣的想法?任何輸入將非常感激。

艾倫

+0

看看視差滾動,有很多工具,如滾動魔術可以幫助你與你正在做的事情。 – TheHamstring

+0

TheHamstring,我試過使用Skollr,我已經用了很多其他的東西,但不能讓它爲我的目的工作。 – user3873905

回答

2

既然你沒有指定jQuery的是否是可以接受的,我扔在一起的東西很快就做到這一點使用普通的JavaScript。我沒有事先爲每個圖像確定合適的滾動距離,而是選擇了在引用數組索引時進行此操作。 (這裏假設你有一個<img id="changeImg">元素):

// Store image sources in array to keep track of them 
var imgArray = ["img1.jpg", 
       "img2.jpg", 
       "img3.jpg"]; 

// Get scrollable height of body, calculate stepsize to go between images 
// Partially taken from http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript 
var body = document.body, html = document.documentElement; 
var totalHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight) - window.innerHeight; 
var stepSize = totalHeight/imgArray.length; 

// Bind to scroll event 
window.onscroll = function(){ 
    var scrolled = document.body.scrollTop; 
    var img = document.getElementById("changeImg"); 

    // Determine correct index to use, and swap src 
    var imgIndex = Math.min(Math.floor(scrolled/stepSize), imgArray.length - 1); 
    img.src = imgArray[imgIndex]; 
}; 

這裏有一個JSFiddle demonstration向您展示在行動代碼。希望這可以幫助!如果您有任何問題,請告訴我。

+0

Serlite,完美的炒作,謝謝!我很欣賞純JavaScript的使用,因爲在這個頁面上只有很少的腳本,所以框架看起來很過分。感謝您的幫助。 – user3873905