2014-07-24 34 views
7

- >請轉到這個問題同步兩個div滾動不順暢iOS中

我想同步兩個div的滾動條,這是編輯的部分如何我這樣做

var div1 = document.getElementById('element1'), 
    div2 = document.getElementById('element2'); 

div1.addEventListener('touchmove', scrolled, false); 
div2.addEventListener('touchmove', scrolled, false); 

function getscrollTop(node) { 
    return node.pageYOffset || node.scrollTop; 
} 

function scrolled() { 

    var node = this, scrollTop = getscrollTop(node); 

    var percentage = scrollTop/(node.scrollHeight - node.clientHeight); 

    var other = document.getElementById({ 
     "element1": "element2", 
     "element2": "element1" 
    }[node.id]); 

    other.scrollTop = percentage * (other.scrollHeight - other.clientHeight); 

}; 

Fiddle - >使用scroll改爲touchmove

但問題是它在低端設備中閃爍,並希望在事件低端設備中使其平滑。

編輯

我用下面的代碼來平滑滾動

var children = document.querySelectorAll('.scrolldiv'); 

var getscrollTop = function(node) { 
    return node.pageYOffset || node.scrollTop; 
}, toInt = function(n) { 
    return Math.round(Number(n)); 
}; 

window.setInterval(function() { 
    var scrollTop = getscrollTop(children[0]); 
    var percentage = scrollTop/(children[0].scrollHeight - children[0].clientHeight); 
    var oscrollTop = percentage * (children[1].scrollHeight - children[1].clientHeight); 
    // console.log(1); 
    children[1].scrollTop = toInt(oscrollTop); 
}, 2); 

設置第二個div時的滾動它催人淚下,在急拉它在桌面瀏覽器,但在iOS的瀏覽器,更順暢一旦滾動完成,感覺設置scrollTop而不是滾動。

+0

也許這會幫助你http://stackoverflow.com/questions/17722497/scroll-smoothly-to-specific-element-on-page – lordkain

+0

我注意到的一件事是在第17行,你正在調用一個函數「getscrollTop (節點)「,你已經有了一個變量scrollTop。此外,你聲明「oscrollTop」作爲變量,然後直接將它分配給函數最後的一個對象......直接將其分配給對象。如果您擔心低端設備的性能,代碼優化非常重要。 – Michael

+0

@邁克爾感謝:) – Exception

回答

4

我不明白爲什麼你必須在這裏計算一個新的百分比,你把它交給第二個滾動的值。這可能是跳動的原因..相反,你可以簡單地從第一個滾動值滾動並將其直接分配給另一個滾動..這將刪除另一個滾動中的生澀..並同步它們..

我剛剛添加了以下行到您的滾動功能的底部.. 其他.scrollTop = getscrollTop(node);

的修飾的功能: -

函數滾動(){

var node = this, 
    scrollTop = getscrollTop(node); 

var id = node.id; 

var percentage = getscrollTop(node)/(node.scrollHeight - node.clientHeight); 

var other = document.getElementById({ 
    "element1": "element2", 
    "element2": "element1" 
}[id]); 

var oscrollTop = percentage * (other.scrollHeight - other.clientHeight) 

//other.scrollTop = oscrollTop; 
//Please note that I have commented out the above line.. and added the following line 
other.scrollTop = getscrollTop(node); 

};

我希望這是你期望的行爲,我在jsfiddle上測試了它,兩個卷軸都很好地同步。

+0

您的解決方案將失敗如果兩個元素有不同的滾動高度 – redV

+0

@redV您好,我相信滾動高度值取相對於它的滾動,併爲這個值傳遞給其他滾動它,使它看起來像實際上是在獲取的值從另一個渦旋,所以不管高度,每個滾動將滾動基於它被傳遞該值相同的高度..因此它仍將同步兩個滾動。 –

+0

是的,你是對的。我認爲不需要計算百分比:) – redV

5

如果你圓你的滾動值的數字爲整數那麼這個問題就會消失:

http://jsfiddle.net/2Cj4S/15/

我只是用一個舍入函數:

function toInt(n){ return Math.round(Number(n)); }; 

,這似乎已經解決了。 Double值確實混淆了GUI小部件,如滾動條和2D繪圖。

+0

感謝您的建議。但我只是刪除滾動處理程序,並使用setInterval的20秒,兩者同步的DIV的滾動位置,現在是相當順利。編輯:同時,我加入您的建議:)我想知道更多關於什麼是背後的整數四捨五入的原因? – Exception

+0

我認爲這是與滾動元件的內圓。我不確定我自己。此外,如果你減少事件(就像你做的那樣),這是一種不會壓倒組件的方式。 –