最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Maintain scroll position in Javascript window.open() - Stack Overflow

programmeradmin3浏览0评论

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>

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>
Share Improve this question asked Dec 16, 2008 at 21:56 Michael KniskernMichael Kniskern 25.3k70 gold badges169 silver badges233 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 11
<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>.
<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.

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.

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.

发布评论

评论列表(0)

  1. 暂无评论