【问题标题】:Preventing scrolling on clicking an internal link防止在单击内部链接时滚动
【发布时间】:2014-04-07 06:59:11
【问题描述】:

我的 html 页面上有一个内部链接。单击内部链接会发生两件事。

  1. 滚动(跳转)页面,使链接的目标位于页面顶部。
  2. url通过显示/abc/#...反映点击的内部链接

我注意到这两个步骤的顺序也是一样的。即hashchange 在滚动发生后被触发。我想阻止滚动但允许 hashchange 发生。如果我写一个onclickevent 来返回false(即阻止它),那么即使hashchange 事件也不会被触发。有什么建议可以做吗?

【问题讨论】:

  • 你试过location.href = '/abc/#'; return false;吗?
  • 我猜你还在尝试......
  • 通过删除具有它所引用的 id 的元素来解决它。找不到元素无法滚动到它。实际上,这个链接是用来打开一个面板的,我们想让生成的 url 成为可收藏的。即,如果我们有 www.domain.org 和一个链接 Show Panel with id xyz,那么这会产生一个类似 www.domain.org#xyz 的 URL,它可以被添加到书签中。我简单地从面板中删除了 id xyz ,因此面板永远不会滚动到顶部。不过谢谢你的回答。

标签: javascript onclick dom-events hashchange internal-link


【解决方案1】:

您可以使用window.history.pushState() 或window.history.replaceState()。这些方法不会滚动。遗憾的是,Internet Explorer 仅从版本 10 开始支持history。

例子:

document.body.addEventListener('click', function(oEvent)
{
    if (oEvent.target.nodeName == 'A'
    &&  oEvent.target.hasAttribute('href')
    &&  oEvent.target.getAttribute('href').charAt(0) == '#')
    {
        oEvent.preventDefault();
        history.pushState(null, '', oEvent.target.getAttribute('href'));
    }
}, false);

PS。我的页面应该在禁用脚本的情况下继续工作,所以我保留元素的 ID,至少在单击某个链接之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2021-09-04
    • 2016-11-07
    • 2018-12-10
    相关资源
    最近更新 更多