如何判断页面是否已跳转到javascript中的锚点(#)? [英] How can I tell if a page has jumped to the anchor (#) in javascript?

查看:601
本文介绍了如何判断页面是否已跳转到javascript中的锚点(#)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些可以出现在许多不同页面上的JavaScript。有时这些页面是通过包含锚引用的URL访问的(例如#comment-100)。在那些情况下,我希望javascript延迟执行,直到窗口跳转。现在我只是使用延迟,但这非常hackish,显然在所有情况下都不起作用。我似乎无法找到任何与跳转窗口相对应的DOM事件。

I have some javascript that can appear on many different pages. Sometimes those pages have been accessed via a URL containing an anchor reference (#comment-100, for instance). In those cases I want the javascript to delay executing until after the window has jumped. Right now I'm just using a delay but that's pretty hackish and obviously doesn't work in all cases. I can't seem to find any sort of DOM event that corresponds to the window "jump".

除了简单的延迟,我唯一的解决方案就是with是让JS在URL中查找锚点,如果找到了,请注意scrollTop中的更改。但这似乎有些错误,而且我不能100%确定我的脚本在滚动发生之前总会被触发,因此只有在用户手动滚动页面时它才会运行。无论如何,我真的不喜欢这个解决方案而且更喜欢更多事件驱动的东西。有什么建议吗?

Aside from the simple delay, the only solution I've come up with is to have the JS look for the anchor in the URL and, if it finds one, watch for changes in scrollTop. But that seems buggy, and I'm not 100% sure that my script will always get fired before the scrolling happens so then it would only run if the user manually scrolled the page. Anyhow, I don't really like the solution and would prefer something more event driven. Any suggestions?

编辑澄清:

我不是想检测哈希变化。请看以下示例:

I'm not trying to detect a hash change. Take the following example:


  1. 页面index.php包含指向post.php的链接#comment-1

  2. 用户点击post.php的链接#comment-1

  3. post.php#comment-1 loads

  4. $(document)。准备火灾

  5. 不久之后,浏览器向下滚动到#comment-1

  1. Page index.php contains a link to post.php#comment-1
  2. User clicks the link to post.php#comment-1
  3. post.php#comment-1 loads
  4. $(document).ready fires
  5. Not long later the browser scrolls down to #comment-1

我'我试图可靠地检测第5步发生的时间。

I'm trying to reliably detect when step 5 happens.

推荐答案

好像你可以使用 window.onscroll 。我刚刚测试了这段代码:

Seems like you could use window.onscroll. I tested this code just now:

<a name="end" />
<script type="text/javascript">
    window.onscroll = function (e) {
        alert("scrolled");
}
</script>

似乎有效。

编辑:嗯,它在IE8中不起作用。它适用于Firefox和Chrome。

Hm, it doesn't work in IE8. It works in both Firefox and Chrome though.

编辑:jQuery有一个 .scroll() 处理程序,但它在浏览IE之前触发,似乎不适用于Chrome或Firefox。

jQuery has a .scroll() handler, but it fires before scrolling on IE and doesn't seem to work for Chrome or Firefox.

这篇关于如何判断页面是否已跳转到javascript中的锚点(#)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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