Angular 1 - $ anchorScroll而不更改URL

时间:2017-11-30 16:32:35

标签: javascript angularjs scroll

我在html中有这些元素:

  <button class="btn"
          type="button"
          ng-click="$ctrl.scrollTo()">
  </button>
<div id="result">
</div>

我的方法scrollTo()

scrollTo() {
  this.$location.hash('result')
}

这很好用,但我想要一个不会改变URL的解决方案(不要在URL中添加#result),如果可能的话,还要添加平滑的滚动。

您的解决方案是否接近我制定的解决方案?

1 个答案:

答案 0 :(得分:2)

$ anchorScroll,因为它的名称在页面上滚动到anchorid,据我所知,它将始终更改网址。但是这个问题有很多不同的解决方案。

一个例子 - 您可以使用原生的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"});

我已为您准备了快速示例:

https://jsfiddle.net/pegla/eoa8v03y/4/