将页面直接加载到锚标记 [英] Load page directly to anchor tag

查看:70
本文介绍了将页面直接加载到锚标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在URL中加载带有哈希标记的页面时,页面会加载然后跳转到锚标记。有没有办法防止这种跳跃,或者通过直接将页面加载到锚标签或者至少使滚动顺畅?

When I load a page with a hash tag in the URL, the page loads and then jumps to the anchor tag. Is there any way to prevent this "jump", either by loading the page directly to the anchor tag or at least making the scrolling smooth?

我在Chrome中看到了这个问题和Firefox,但不是IE。

I see this problem in Chrome and Firefox, but not IE.

推荐答案

如果你仍然遇到跳跃问题,你可以使用jQuery:

If you're still experiencing the jumping issue, you could something with jQuery:

//Use a RegEx pattern to search for an id, if present
var pattern = new RegExp('\#(.*)');
var id = pattern.exec(window.location)[0].replace('#','');
//Prevent the browser's default behavior of jumping to the id
document.location = '#';
//When the page finishes loading, smoothly scroll to the specified content
$(document).ready(function() {
    if(id != "") {
        $('html,body').animate({
            scrollTop: $('#' + id).offset().top,
        }, 650);
    }
});

请注意,这仅适用于每页加载一次。

Note that this will only work once per page load.

这篇关于将页面直接加载到锚标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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