简体   繁体   English

为什么此脚本不执行scrollTo(x,y)JavaScript?

[英]Why does this script not execute scrollTo(x,y) javascript?

Hello I am trying to create a refresh script to refresh a page on incomming messages,updated posts,ect. 您好,我正在尝试创建刷新脚本来刷新有关传入消息,更新帖子等的页面。 Why is x,y not executed useing ex: 1? 为什么不使用ex:1执行x,y? I have seen a few different methods of reloading a page and keeping scroll position but they seem overkill. 我已经看到了几种重新加载页面并保持滚动位置的不同方法,但是它们似乎过分了。 I think I would like to use ex: 2, is there any logical way to clear the server side variables using reload() or should I go another route for something like this? 我想我想使用ex:2,是否有任何逻辑方法可以使用reload()清除服务器端变量,还是我应该走另一条路线来实现类似目的?

    function Refresh()
    {

        var x = window.pageXOffset;
        var y = window.pageYOffset;

        //ex 1:this works but doesnt keep scroll position
        //window.location = window.location.href;

        //ex 2: this works and retains x,y but doesnt refresh $_POST $_GET server side variables
        window.location.reload();

        window.location.scrollTo(x,y);
    }
    //for testing only
    setInterval('Refresh()', 5000);

scrollTo is not executed because that line is never reached and also wrong. 未执行scrollTo,因为永远不会到达该行并且也是错误的。 The moment you trigger a page load, script execution stops. 一旦触发页面加载,脚本执行就会停止。 Furthermore, window.location refers to the address-bar, basically, and scrollTo does not make sense here. 此外,window.location基本上是指地址栏,而scrollTo在这里没有意义。 Better would be window.scrollTo, but never mind: 最好是window.scrollTo,但不要紧:

A reload preserves scroll position (in most browsers) and $_GET variables, however browsers usually want user-confirmation to reload a POST-request. 重新加载会保留滚动位置(在大多数浏览器中)和$ _GET变量,但是浏览器通常需要用户确认来重新加载POST请求。 You probably do not want that behaviour. 您可能不希望这种行为。

The least "overkill" way to make the browser scroll to new content is using hash-tags, assuming you are in control of the updated content. 假设您可以控制更新的内容,则使浏览器滚动到新内容的“最小化”方法是使用哈希标签。 Just append something like #newcontent to your URL and set the id of your new content: 只需在URL后面附加#newcontent之类的内容,然后设置新内容的ID:

<div id="newcontent">Cool new post... 

Browsers will auto-scroll to a fragment identifier . 浏览器将自动滚动到片段标识符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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