简体   繁体   中英

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:

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. 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).

My issue occurs with 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). I can't really use event.preventDefault() because I don't have any event parameter. 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. What if you changed the location before scrolling ?

Otherwise, you could use window.history.replaceState method which should modify the URL without scrolling. However, bear in mind that's it is not supported in all browsers yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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