2017-03-02 110 views
0

我想(有點)模仿使用本機JavaScript的平滑滾動。我非常接近我想要的,但是我的邏輯一直滾動到頁面底部[LINK TO PAGE]。您可以單擊「其他作品」鏈接查看當前的滾動行爲並打開控制檯以查看調試語句。JavaScript同步setTimeout使用IIFE

<script type="text/javascript"> 
    var el = document.querySelector('a[href="#other-works"]'); 
    var otherEl = document.querySelector('#other-works') 
    el.onclick = function() { 
     var i = 0; 
     var distance = otherEl.offsetTop - document.body.scrollTop; 
     console.log("distance: ", distance); 
     var pixelJump = 25; 
     (function loop() { 
      console.log("i: ",i); 
      console.log("current scrollTop: ", document.body.scrollTop) 
      if (i + pixelJump > distance) { 
       document.body.scrollTop = otherEl.offsetTop; 
       console.log('its over') 
       return; 
      } 
      if (i > distance) return; 
      i += pixelJump; 
      scrollBy(0, pixelJump); 
      console.log("new height: ", document.body.scrollTop) 
      setTimeout(loop, 50); 
     })(); 
    } 
</script> 

我添加了console.log語句來嘗試和調試。這裏是一個輸出示例:

scroll distance required: 2910 
i: 0 
current scrollTop: 478 
new height: 503 
i: 25 
current scrollTop: 3388 ##### Why does scrollTop jump to 3388??? ####### 
new height: 3413 
i: 50 
current scrollTop: 3413 
new height: 3438 
i: 75 
+0

請在問題本身而不是第三方網站上提供[mcve]中的所有相關代碼。 –

回答

-1

對不起,但我仍然不完全確定你想達到什麼。

必須在創建一個簡單的插件:

https://github.com/drozdek/addListviewPointers

這是有幫助嗎?

+0

請僅使用* Post answer *按鈕才能得到實際答案。一旦你有[足夠的代表](https://stackoverflow.com/help/privileges/comment),你就可以添加評論的問題。如果你想宣傳你的插件,你必須包括如何使用該插件的代碼來解決OP的具體問題。 –

+0

這不是一個廣告 - 試圖幫助,就是這樣。你的方法和解釋很有趣... – Raphael

+0

而我試圖幫助你沒有刪除你的答案。閱讀[答案],標題爲「爲鏈接提供上下文」一節。還有一段文字「具體來說,這個問題是要求的嗎?確保你的答案提供了 - 或者一個可行的選擇。」從這個答案:*我還不完全確定你想達到什麼*。這應該是對問題的評論,而不是回答。 –