Javascript setTimeout() 和窗口函数

发布于 2024-11-30 11:54:12 字数 553 浏览 2 评论 0原文

以下 JavaScript 代码在 Chrome 中运行,并导致“背景”窗口的大小调整为我的规格:

var background;
function play () {
    var w  = screen.width;
    var h  = screen.height;
    if( !background || background.closed ) background = window.open("background.html", "It's a pop-up!", "top="+ 100 +",left="+ 770 +",width="+ w/3 +",height="+ h/3 +",location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no");
    background.resizeTo(w,724);
}

但是,当我尝试延迟调整大小功能时,代码会中断。为什么调用 setTimeout("background.resizeTo(w,724)",10000) 没有可见结果?

The following JavaScript code runs in chrome, and results in the "background" window being resized to the my specifications:

var background;
function play () {
    var w  = screen.width;
    var h  = screen.height;
    if( !background || background.closed ) background = window.open("background.html", "It's a pop-up!", "top="+ 100 +",left="+ 770 +",width="+ w/3 +",height="+ h/3 +",location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no");
    background.resizeTo(w,724);
}

When I try to delay the resize function, however, the code breaks. Why does calling setTimeout("background.resizeTo(w,724)",10000) have no visible result?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赴月观长安 2024-12-07 11:54:12

将其更改为

setTimeout(function(){background.resizeTo(w,724);},10000);

您应该传递一个函数。这是正确的解决方案,在使用 setTimeout()setInterval() 时,不要依赖将字符串作为“函数”传递,它会更慢,因为它必须进行评估,这是不正确的。

此外,您可能会遇到范围问题(如您的示例中所示)。仅当 backgroundw 都是全局时,您的代码才有效。我们不知道 background,但 w 绝对只是 play 的本地内容。传递一个关闭这些变量的函数(闭包)而不是字符串,可以解决这个问题。

有关它的更多信息: https://developer.mozilla.org/en/DOM /window.setTimeout#语法

Change it to

setTimeout(function(){background.resizeTo(w,724);},10000);

You should pass a function. This is the proper solution, don't ever rely on passing a string as a 'function' when using setTimeout() or setInterval(), it's slower because it has to be evaluated and it just isn't right.

Furthermore you may have problems with the scope (like in your example). Your code would only work if both, background and w are global. We don't know about background, but w is definitely only local to play. Passing a function which closes over those variables (a closure) instead of a string, solves this problem.

For more info about it: https://developer.mozilla.org/en/DOM/window.setTimeout#Syntax

国产ˉ祖宗 2024-12-07 11:54:12

因为整个语句基本上已经被评估了,w 已经没有任何意义了。

试试这个:

setTimeout('background.resizeTo('+w+',724',10000);

Because the entire statement is basically eval'd and w has no meaning anymore.

try this:

setTimeout('background.resizeTo('+w+',724',10000);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文