jQuery或js检测何时在地址栏上的相同哈希码URL上输入 [英] jquery or js detect when hit enter on same hashcode url on address bar

查看:146
本文介绍了jQuery或js检测何时在地址栏上的相同哈希码URL上输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面顶部带有粘性菜单栏。此页面上有一些内部链接。当我单击内部链接时,页面滚动和具有哈希码ID的元素将移至顶部。但标题隐藏在粘性菜单中。因此,在窗口加载时,我已经编写了js代码,请参见下文:

I have a page with sticky menu bar in top. There are some internal links on this page. when I click on internal link, page scrolls and element having hashcode id moves to top. but heading hides in sticky menu. So on window load I have written js code, see below:

if(window.location.hash) {
        var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
        console.log (hash);
        if(hash && $("#"+hash).length){
            $("#"+hash).css('padding-top', '80px');
        }
        $(window).scroll(function() {
            $("#"+hash).css('padding-top', '0');
        });
    }

在使用哈希码URL加载页面时,它的工作正常。

its working fine when page loads with hashcode url.

问题是,当用户单击地址栏且未更改任何内容时,按enter键,则具有id作为哈希码agian的元素移动到顶部,这一次我的js代码无法运行,并且标题隐藏在粘滞菜单中。

Problem is that when user click on address bar and without changing anything press enter, then element having id as hashcode agian moves to top and this time my js code not run and heading is hides in sticky menu.

那么当地址栏聚焦并按下Enter键时,有什么方法可以检测到此事件?

So is there any way to detect this event when address bar is focused and enter key is pressed?

还是这种情况还有其他解决方案吗?

or is there any other solution for this situation?

谢谢

推荐答案

我用以下逻辑得出了一个简单的解决方案。请注意,我目前还不完全了解在其他情况下会触发窗口对象中的焦点事件。如果遇到副作用,我将更新我的帖子。

I came to a simple solution with the following logic. Be aware that i currently don't completely know in which other circumstances the 'focus' event in the window object is fired. I will update my post if i encounter side effects.

据我发现,Chrome浏览器会执行整页加载,而Firefox会按照您的描述进行操作。因此,在重新加载页面之前会触发Chrome中的焦点事件,这应该在您的实现中考虑。 (我在'DOMContentLoaded'中也有重新定位逻辑,所以这种情况对我来说很好)

As far as i found out, Chrome does a full page load where Firefox just does what your description said. Thus the focus event in Chrome is fired BEFORE the page reloads, which should be considered into your implementation. (I have the repositioning logic within 'DOMContentLoaded' too, so this case is fine for me)

window.addEventListener('focus', function() {

    // Do the repositioning actions

});

更新

以下情况也会触发焦点事件:

The focus event is also fired if you:


  • 单击标题栏

  • 最小化并最大化浏览器窗口

  • 在任务栏中切换程序并切换回浏览器

这篇关于jQuery或js检测何时在地址栏上的相同哈希码URL上输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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