Maintain scroll position in Javascript window.open()

岁酱吖の 提交于 2019-12-10 16:01:52

问题


How do I maintain the scroll position of the parent page when I open new window using window.open()? The parent page returns to the top of the page.

Here is my current code:

<a href="#" onclick="javascript: window.open('myPage.aspx');">
   Open New Window
</a>

回答1:


<a href="#" onclick="window.open('myPage.aspx');return false;">Open New Window</a>
  • javascript: is not required in event attributes.
  • You were not returning false from the event handler, so the link was being following, it was equivilent to <a href="#">Scroll to top</a>.



回答2:


<a href="javascript:void()" onclick="window.open('myPage.aspx');">Open New Window</a>

Ought to do it. As others have mentioned, the # is trying to go to a non-existent anchor, which will cause the browser to scroll to the top. You don't want to remove the href attribute, because some browsers don't treat <a> tags without href attributes as links for styling purposes, and you would have to define additional CSS rules to ge thte link to look like other links on your site.

Also, why have an href attribute and then try to block the event by always returning false from your handler. In my opinion, this way is cleaner than the others proposed here.




回答3:


I think the problem is that your link is pointing to an empty # (href="#"), which the browser will interpret to mean "the top of the page".

Try removing the href attribute from your anchor tag. The onclick attribute should be enough for what you need.




回答4:


It is good to keep the page accessible for those that don't have javascript, or have it disabled:

<a href="myPage.aspx" target="_blank" onclick="window.open('myPage.aspx');return false;">Open New Window</a>

The target="_blank" is to open in a new window (or tab). If the client does not have JS, then it will still open the page, just not in a JS invoked window.



来源:https://stackoverflow.com/questions/372907/maintain-scroll-position-in-javascript-window-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!