--- tags: 開發日誌 --- # 【Angular】Swiper scrollTop = 0 沒作用 試圖在 Swiper 觸發 slideChange 讓新的 slide 可以自動滾動到該 component 頂部,使用 window.scrollTo(0, 0) 和 scrollTop = 0 沒有作用。 ## 解決方式 ```javascript= const targetElement = this.el.nativeElement; // 抓取目標el targetElement.scrollTop = 0; // 可以再增加平滑屬性,讓視覺上的滾動比較自然 // targetElement.scrollTo({top:0,behavior: "smooth"}) ``` 這邊要注意一下,如果要取得 scrollTop 的值,要抓的是滾動層的的父層,而要滾動的容器外面 均設為不能滾動。 ## 其他方式 [Element.scrollIntoView()](https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView) [那些被忽略但很好用的 Web API / ScrollIntoView](https://ithelp.ithome.com.tw/articles/10279669?sc=iThelpR) ```javascript= const targetElement = this.scroll.nativeElement; targetElement.scrollIntoView({ behavior: "smooth" }); ``` 不過經過測試,在 ChromeWeb、Android 中,如果 slideChange 時去呼叫沒有作用。 ## 參考相關資料 * [How to handle window scroll event in Angular 4?](https://stackoverflow.com/questions/44516017/how-to-handle-window-scroll-event-in-angular-4/44516191) * [Angular4 - Scrolling to anchor](https://stackoverflow.com/questions/44441089/angular4-scrolling-to-anchor) * [Angular 5 Scroll to top on every Route click](https://stackoverflow.com/questions/48048299/angular-5-scroll-to-top-on-every-route-click/48048822) * [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)