為了改善您的使用體驗,本網站正在進行維護,部分功能暫時無法使用。若本站的文件無法解決您的問題,想要向社群發問的話,請到 Twitter 上的 @FirefoxSupport 或 Reddit 上的 /r/firefox 發問,我們的社群成員將很快會回覆您的疑問。

搜尋 Mozilla 技術支援網站

防止技術支援詐騙。我們絕對不會要求您撥打電話或發送簡訊,或是提供個人資訊。請用「回報濫用」功能回報可疑的行為。

了解更多

Id in url is not locating element in DOM on page load.

more options

I am working on a server-side rendered app which uses a templating language to render HTML. Before submitting a form the user has the option go back and change one of their inputs. This is achieved by adding the ID ref that I want to scroll to the end of the href URL.

e.g. <a href="/form/edit#form-error>Change</a> would go to the /form/edit page and automatically scroll to the element with an ID of form-error.

This works perfectly well in Chrome and Edge. However, in Firefox the page simply renders in the centre. A page refresh does the same thing. However, if i click the url bar and press enter it scrolls to said element. I think Firefox maybe loads DOM elements, javascript etc in a different order is the issue? Any help with this much appreciated!

I am working on a server-side rendered app which uses a templating language to render HTML. Before submitting a form the user has the option go back and change one of their inputs. This is achieved by adding the ID ref that I want to scroll to the end of the href URL. e.g. <a href="/form/edit#form-error>Change</a> would go to the /form/edit page and automatically scroll to the element with an ID of form-error. This works perfectly well in Chrome and Edge. However, in Firefox the page simply renders in the centre. A page refresh does the same thing. However, if i click the url bar and press enter it scrolls to said element. I think Firefox maybe loads DOM elements, javascript etc in a different order is the issue? Any help with this much appreciated!

所有回覆 (2)

more options

Navigation to anchors is based on vertical distance from the top of the page. If the position of the element changes after Firefox initially computes it, Firefox usually ignores that later change. You can use a script to fix the position after load, for example:

    var elId = window.location.hash;
    if (elId.length > 1){
        el = document.getElementById(elId.substr(1));
        el.scrollIntoView({block: "center"});
    }

I guess the question is how/when to fire it. Does your application already have some code that runs on load or on pageshow?

more options

Thanks jscher2000 for such a quick reply. Sadly I don’t think this will work for me. My app is rendered via a templating engine/node so window, document etc isn’t available to me. Also I can’t attach a script to the rendering file as it is a form page so would be vulnerable to XSS attacks.