Why do page anchors sometimes miss?

后端 未结 7 1541
灰色年华
灰色年华 2020-12-15 05:41

On an HTML page, a link like this:

Location on Page

...should navigate to this spot on the

相关标签:
7条回答
  • 2020-12-15 06:21

    JS Solution

    Run this function on document ready.

     function goToAnchor() { 
        hash = document.location.hash;
        if (hash !="") {
            setTimeout(function() {
                if (location.hash) {
                    window.scrollTo(0, 0);
                    window.location.href = hash;
                }
            }, 1);
        }
        else {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-15 06:23

    Quite often the scrolling can occur before the page has finished loading. If you have images without widths and heights, the page will jump, then load the image and re-layout itself, making the place you previously jumped to seem wrong.

    Edit: Anything else that can change page layout should also be considered with suspicion... this include javascript and CSS that's not loaded in the <head> (never mind that all CSS should be loaded in the head; it isn't always).

    If the page is bounced through a redirect, I believe IE will scroll the end page but Firefox won't.

    0 讨论(0)
  • 2020-12-15 06:32

    Note that you can add id="pagelocation" to just about any HTML element, for the same result, which saves you adding the additional anchors for link destinations.

    0 讨论(0)
  • 2020-12-15 06:35

    As mentioned above, this is probably due to images being rendered late and 'adjusting' the layout as they load.

    If you can specify the size of the images then that much room can be allocated before they render, which should prevent the problem.

    As a side note I've had this problem before in the form of using forward/back between enough pages that the images needed reloading, causing me to end up in the wrong place after they had rendered.

    0 讨论(0)
  • 2020-12-15 06:39

    I believe the behavior you are seeing is the result of the browser locating to that spot on the page before all images have finished loading. Once the images finish loading, then the layout of the page has changed (the page is likely longer vertically, for example), causing the location of where the anchor should be to have changed - but the browser still thinks it has already navigated to that anchor.

    0 讨论(0)
  • 2020-12-15 06:39

    I have also seen this happen when JavaScript creates a drop-down menu at the top of a page. Then, once the menu has been finished, it is hidden, scrolling up the content below.

    In the meantime, the browser has already set the target location at the top of the window. Hiding the menu a the very top of the page moves the target location up off the top of the window.

    0 讨论(0)
提交回复
热议问题