2015-04-24 136 views
9

我在如何做到這一點的損失。滾動頁面然後在certian位置滾動元素

我有一個網頁。我想要一個用戶向下滾動,然後在距離頂部的特定距離處,我希望鼠標滾動以實現元素位置(使其顯示爲元素正在滾動的思想)。那麼當這個元素碰到一個位置(即頂部:-500)時,我希望滾動再次應用到主網頁。有關我如何做到這一點的任何想法?

IM在小提琴的工作,但現在沒有任何運氣,當我有東西給

編輯,我將發佈:附一解決方案/須藤代碼https://jsfiddle.net/vk0jk37v/23/

剛開始是一個的圖像我正在應用這個領域。

//pageFeature.style.backgroundPosition = "0px " + parseInt(-y/6) + 'px'); 

var element = document.getElementById('container').getBoundingClientRect(); 
var elementTop = element.top //distance from top 720; 

// variable to stop function from being replayed on scroll when scrolling image 
var isScrollingImage = false; 

// disables scroll on body 
var disableScroll = function() { 
    document.body.style.overflow='hidden'; 
} 
// enables scroll on body 
var enableScroll = function() { 
    document.body.style.overflow='auto'; 
} 
//change position of background along y axis with scroll 
var scrollImage = function() { 
    console.log("called"); 
    isScrollingImage = true; 
    var pageFeature = document.getElementById("inner"); 
    var pageFeaturePosition; 
    pageFeature.style.backgroundPositionY=parseInt(-scrollY/10) + "px"; 
    //if (background is scrolled to bottom) { 
    // enableScroll(); 
    // } 
} 

//when element gets to center of viewport and animation is scroll is not on element 
//call scrollImage() 
function checkPosition() { 
    if (scrollY > 720 && !isScrollingImage) { 
     disableScroll(); 
     scrollImage(); 
    } 
    //isScrollingImage = false; 
} 

//once out of view port will have to bring the image back down, 
//scroll image will only happen on the way down 

document.addEventListener('scroll', checkPosition); 

enter image description here

+0

您可以使用onscroll事件並檢查一次該元素在所需位置的位置。您可以將頁面滾動回其位置 – Panther

+0

您是否像45分鐘前一樣提問? 。至少在有人發佈答案的情況下檢查答案。並改變標題並沒有減少重複的問題 –

+0

嗨阿爾瓦羅,我現在正在查看你對我最後一個問題的答案,並會在一分鐘後發佈。在另一個問題,我正在尋找一個CSS解決方案,並與這一個我正在尋找一個JS解決方案。我關心我的佈局,我可能不得不看看使用js來做到這一點(我正在將這個應用於多個環境中)。謝謝你在另一個問題上的迴應。對於任何有興趣的人他指的是http://stackoverflow.com/questions/29852865/allow-scroll-of-div-set-behind-another-div – ReganPerkins

回答

3
var thresholdY = 150; 
    var thresholdCounter = 0; 
    var speed = 4; 
    var element = document.getElementById('yourElement'); 

    window.onscroll = function(event) { 
     if(scrollY > thresholdY) { 
     window.scrollTo(0, thresholdY); 
     element.setAttribute('style', 'transform:translate3d(0,' + (--thresholdCounter * speed) + 'px,0);'); 
     return false; 
     } 
     return null; 
    }; 

這裏有一個演示:https://jsfiddle.net/pkt6xnb5/

這裏的想法是,你保持窗口的地方,當用戶達到一定的閾值Y位置。同樣在那個時候,我們沿着與Y軸相反的方向將元素轉換爲用戶滾動的方向,以使其向上滾動。那是你在找什麼?

+0

嗨benny我認爲這將工作,我只是努力讓它在我的小提琴工作(我需要滾動鼠標/標籤不僅僅是一個動畫,但我認爲這個邏輯將工作)控制。當我有它的工作時,我會將答案標記爲正確。謝謝! – ReganPerkins

+0

@ReganPerkins啊好吧,可能有一些方法可以做到這一點。我還沒有測試過,但這似乎應該工作(編輯答案) – Benny

+0

@ReganPerkins好吧,我有時間去電腦,現在我意識到它有點複雜。這個小提琴應該適合你要求的功能,但是你必須編寫額外的邏輯才能使其反向工作(如果這是你想要的):https://jsfiddle.net/pkt6xnb5/ – Benny