【问题标题】:Highlight the element I enter with its id突出显示我输入的元素及其 id
【发布时间】:2015-10-19 14:19:24
【问题描述】:

我想要的东西与我们在 stackoverflow 中的东西非常接近。 考虑我有一个这样的页面:“myPage.com”。 然后考虑在搜索后我想将用户重定向到此页面,但正是在所需的元素上,例如:“myPage.com#123”。 如您所知,“123”是我希望页面滚动到它的元素的 ID。 但问题是滚动是不够的。我想用 JQuery 做额外的工作,我想知道如何向它添加事件处理程序。更直接一点,这个事件是什么?

【问题讨论】:

    标签: jquery html


    【解决方案1】:

    最简单的方法是检查文档的哈希值,如下所示:

    $(function() {
        // assign value of hash to hash variable
        var hash = window.location.hash;
    
        // check if hash isn't undefined
        if (hash) {
            // target element with id from hash
            var $where = $(hash);
            // animate scroll to position of element from hash
    	$('html, body').animate({ scrollTop: parseInt($where.position().top) + 'px' }, 300);
        } else {
            // there is no hash ;-)
    	alert('no hash');
        }
    });

    还有onhashchange事件:

    https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange

    【讨论】:

    • 这在页面加载方面会很好,但问题是我会有一个页面内搜索!这将链接到同一页面中的 id。这个答案很好,我可以手动处理这些事情,但如果有任何关于哈希的通知,它会更好。谢谢。
    • 很高兴我能帮上忙 ;-)
    【解决方案2】:

    您可以将事件侦听器添加到加载事件。然后get the Anchor(#123),然后随心所欲地使用它。

    对于滚动,#123 足以让浏览器了解你想要什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-30
      • 2014-12-26
      • 2013-03-01
      • 2014-11-14
      • 2015-02-11
      • 2019-10-02
      • 1970-01-01
      相关资源
      最近更新 更多