【问题标题】:How to perform javascript if url has anchor [duplicate]如果 url 有锚点,如何执行 javascript [重复]
【发布时间】:2013-03-05 15:48:35
【问题描述】:

与 SO 类似,我想为一些评论设置一个锚点,并且在页面加载后我希望页面执行一些 javascript(突出显示、滚动等 - 我可以自己编写)

所以如果我的网址是

www.mywebapp.com/mypost#45625

我希望 javascript 滚动到 id 为 45625 的 div 并在那里执行我自己的 javascript。

如何编写开始执行我的 javascript 的条件,以便它仅在存在 achor 时才有效?

【问题讨论】:

  • 这是自动完成的。试试看。
  • @Blender, “然后在那里做一些事情。”
  • 使用id="45625" 而不是id="#45625"

标签: javascript anchor


【解决方案1】:
if (window.location.href.indexOf('#') > -1)
    // Do something.

甚至更好:

if (window.location.hash.length)
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 2012-10-01
    • 2017-06-18
    相关资源
    最近更新 更多