无需页面滚动即可修改location.hash [英] Modifying location.hash without page scrolling

查看:150
本文介绍了无需页面滚动即可修改location.hash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一些页面使用ajax来加载内容,在某些情况下,我们需要深度链接到页面.与其链接到用户"并告诉人们单击设置",不如将其链接到 user.aspx#settings

We've got a few pages using ajax to load in content and there's a few occasions where we need to deep link into a page. Instead of having a link to "Users" and telling people to click "settings" it's helpful to be able to link people to user.aspx#settings

为了使人们能够为我们提供指向各节的正确链接(用于技术支持等),我将其设置为在单击按钮时自动修改URL中的哈希.当然,唯一的问题是,发生这种情况时,它还会将页面滚动到该元素.

To allow people to provide us with correct links to sections (for tech support, etc.) I've got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element.

是否可以禁用此功能?到目前为止,这是我目前的操作方式.

Is there a way to disable this? Below is how I'm doing this so far.

$(function(){
    //This emulates a click on the correct button on page load
    if(document.location.hash){
     $("#buttons li a").removeClass('selected');
     s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:","");
     eval(s);
    }

    //Click a button to change the hash
    $("#buttons li a").click(function(){
            $("#buttons li a").removeClass('selected');
            $(this).addClass('selected');
            document.location.hash=$(this).attr("id")
            //return false;
    });
});

我曾希望return false;可以阻止页面滚动-但这只会使链接根本不起作用.因此,现在暂时将其注释掉,以便我进行导航.

I had hoped the return false; would stop the page from scrolling - but it just makes the link not work at all. So that's just commented out for now so I can navigate.

有什么想法吗?

推荐答案

我想我可能已经找到了一个相当简单的解决方案.问题在于URL中的哈希也是滚动到页面上的元素.如果我只是在哈希前面添加一些文本,那么现在它不再引用现有元素!

I think I may have found a fairly simple solution. The problem is that the hash in the URL is also an element on the page that you get scrolled to. if I just prepend some text to the hash, now it no longer references an existing element!

$(function(){
    //This emulates a click on the correct button on page load
    if(document.location.hash){
     $("#buttons li a").removeClass('selected');
     s=$(document.location.hash.replace("btn_","")).addClass('selected').attr("href").replace("javascript:","");
     eval(s);
    }

    //Click a button to change the hash
    $("#buttons li a").click(function(){
            $("#buttons li a").removeClass('selected');
            $(this).addClass('selected');
            document.location.hash="btn_"+$(this).attr("id")
            //return false;
    });
});

现在,URL显示为page.aspx#btn_elementID,它不是页面上的真实ID.我只是删除"btn_"并获取实际的元素ID

Now the URL appears as page.aspx#btn_elementID which is not a real ID on the page. I just remove "btn_" and get the actual element ID

这篇关于无需页面滚动即可修改location.hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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