简体   繁体   English

阻止对位置设置进行默认操作

[英]Prevent default action on location setting

I modified a pretty common jQuery smooth-scroll method to suit my needs better --- a function to scroll to an anchor: 我修改了一个非常普通的jQuery平滑滚动方法以更好地满足我的需求---滚动到锚点的函数:

function scrollToAnchor(id, offset) {
    target = $(id);
    $('html, body').stop().animate({
        'scrollTop': target.offset().top + offset}, 900, 'swing', function () {
            window.location = id;
            });
    }

I have the offset parameter to account for a fixed navigation pane at the top. 我有offset参数来说明顶部的固定导航窗格。 I have the offset set to -100 on each call of scrollToAnchor so that it scrolls 100 pixels less (this allows the content to be displayed without the fixed navigation pane hiding any content). 我将对scrollToAnchor每次调用的偏移量设置为-100,以便它滚动少100个像素(这使内容得以显示,而固定的导航窗格没有隐藏任何内容)。

My issue occurs with window.location = id; 我的问题发生在window.location = id; . This sets the URL to include the anchor, but because of this, it scrolls to the top of the div (this hides 100 pixels of content that my offset tries to prevent). 这会将URL设置为包括锚点,但由于这个原因,它滚动到div的顶部(这隐藏了100像素的内容,我的偏移量试图阻止该内容)。 I can't really use event.preventDefault() because I don't have any event parameter. 我真的不能使用event.preventDefault()因为我没有任何事件参数。 Is there any way to prevent the window from scrolling when I set the location? 设置位置时,有什么方法可以防止窗口滚动?

As you pointed out, it's the browser default behavior to scroll to the element specified by the anchor you add in the URL. 正如您所指出的那样,滚动到URL中添加的锚点所指定的元素是浏览器的默认行为。 What if you changed the location before scrolling ? 如果滚动之前更改了位置怎么办?

Otherwise, you could use window.history.replaceState method which should modify the URL without scrolling. 否则,您可以使用window.history.replaceState方法,该方法应修改URL而无需滚动。 However, bear in mind that's it is not supported in all browsers yet. 但是,请记住, 并非所有浏览器都支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM