$ anchorScroll和$ location仅在第二次尝试后才能工作 [英] $anchorScroll and $location only work after second try

查看:62
本文介绍了$ anchorScroll和$ location仅在第二次尝试后才能工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $ anchorScroll $ location.hash()滚动到 div .我在页面顶部有一个底部.当我单击底部时,我希望页面向下滚动到我具有< div id ="target"> 的页面底部.

I am trying to use $anchorScroll and $location.hash() to scroll to a div. I have a bottom on the top of the page. When I click the bottom, I want the page to scroll down to the bottom of the page where I have a <div id="target">.

由于某种原因,我第一次单击该按钮时,页面不会滚动.如果第二次单击,页面会滚动.然后滚动工作正常.如果刷新页面,可以重现这种怪异的行为.

For some reason, the first time I click the button, my page doesn't scroll. If a click a second time, the page does scroll. And afterwards the scrolling works fine. This weird behavior can be reproduced if I refresh my page.

我的控制器中有以下代码:

I have this code in my controller:

$scope.scrolldown = function() {
  $location.hash('target');
  $anchorScroll();
}

我知道 $ location.hash('target')行应该在我的URL末尾附加一个哈希值.

I know that the $location.hash('target') line is supposed to append a hash value to the end of my URL.

这是我的页面首次加载时的URL:

Here's the URL when my page first got loaded:

http://run.plnkr.co/iqvdGjdeCP4idP4D/

第一次单击按钮后,它变为:

After I clicked my button for the 1st time, it becomes:

http://run.plnkr.co/iqvdGjdeCP4idP4D/#/target

这不正确(页面无法正确滚动).

which was not right (and the page was not scrolling properly).

第二次单击按钮后,它变为:

After I clicked my button for the 2nd time, it becomes:

http://run.plnkr.co/iqvdGjdeCP4idP4D/#/target#target

从这一点开始,页面开始正确滚动,但是URL对我来说仍然很奇怪-为什么我要两个哈希值?

From this point on the page started to scroll properly, but the URL still looks very strange to me -- why would I want two hash values?

我想知道为什么按钮仅在第二次单击后才能起作用,以及如何更正它.

I want to know why the button only works after second click and how to correct it.

我在我的代码中添加了路由,并且滚动条现在可以正常工作了.这是我的带有路由的插件演示.

I added routing to my code and the scroll is working fine now. Here's my plunker demo with routing.

推荐答案

看看这个问题,其中包含一个可能的解决方案:在查询中基于视图的ui路由器重新加载参数更改

Take a look at this question, which contains a possible solution for you: Supress reloading of ui-router based view on query parameter change

第二次单击该按钮有效,因为哈希值不会更改(因此不会重新加载路由).注意第一次单击时页面闪烁吗?这表明整个DOM已重新渲染.

It works the second time you click the button because the hash doesn't change (and so the route doesn't reload). Notice the page flickering when you click it the first time? That's an indicator that the whole DOM has been re-rendered.

这篇关于$ anchorScroll和$ location仅在第二次尝试后才能工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆