我的 html 中有这些元素:
<button class="btn"
type="button"
ng-click="$ctrl.scrollTo()">
</button>
<div id="result">
</div>
我的方法 scrollTo()
:
scrollTo() {
this.$location.hash('result')
}
这很好,但我想要一个不更改 URL 的解决方案(不要在 URL 中添加#result),并且如果可能的话添加平滑滚动。
你有接近我的解决方案的解决方案吗?
最佳答案
$anchorScroll,顾名思义,滚动到页面上的 anchor
或 id
,据我所知,它总是会更改 URL。但是这个问题有很多不同的解决方案。
一个示例 - 您可以使用 native scrollIntoView(检查兼容性,但它适用于所有体面的浏览器,甚至是 IE8):
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
所以你会做这样的事情来获得平滑的滚动效果:
// play around with options if you want - you can put block: "start" which doesn't play very nice with jsfiddle but should work fine on any machine.
$window.document.getElementById(id).scrollIntoView({behavior: "smooth", block: "end"});
我已经为你准备了简单的例子:
关于javascript - Angular 1 - $anchorScroll 不改变 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47578209/