【问题标题】:setTimeout function doesn't work in popup windowsetTimeout 函数在弹出窗口中不起作用
【发布时间】:2014-07-02 05:33:14
【问题描述】:

我有一个弹出窗口,它应该提醒你这个弹出窗口将在 10 秒后关闭,它显示弹出窗口但 setTimeout 不起作用,它通过单击按钮关闭,但它本身在 10 秒内不会关闭.我做错了什么?我尝试单独设置 setTimeout 函数,或者通过字符串设置,都没有。

P.s:我知道我可以通过 alert 来做到这一点,但它看起来不像弹出窗口那样漂亮:)

function myPop() { 
    this.square = null;
    this.overdiv = null;
    this.popIn = function() {
        if (this.square != null) {
            document.body.removeChild(this.square); 
            //setTimeout('alert("прошла секунда")', 10000);
            this.square = null;
        }
        if (this.overdiv != null) {
            document.body.removeChild(this.overdiv);
            //setTimeout('alert("прошла секунда")', 10000);
            this.overdiv = null;
        }
    }
    this.popOut = function(msgtxt) {
        //filter:alpha(opacity=25);-moz-opacity:.25;opacity:.25;
        this.overdiv = document.createElement("div");
        this.overdiv.className = "overdiv";

        this.square = document.createElement("div");
        this.square.className = "square";
        this.square.Code = this;
        var msg = document.createElement("div");
        msg.className = "msg";
        msg.innerHTML = msgtxt;

        this.square.appendChild(msg);
        // var closebtn = document.createElement("button");
      /**closebtn.onclick = setTimeout(function(){
          this.parentNode.Code.popIn();},10000);*/

        setTimeout(function() {
            this.parentNode.Code.popIn();},10000);


        //closebtn.innerHTML = "Жабу";
        //this.square.appendChild(closebtn);

        document.body.appendChild(this.overdiv);
        document.body.appendChild(this.square);
    }
}

任何帮助将不胜感激

【问题讨论】:

    标签: javascript popup settimeout


    【解决方案1】:

    setTimeout 中的回调函数正在访问不正确的 this。在setTimeout 内,this 将指 Window。窗口没有父节点。试试这个:

    var that = this;
    setTimeout(function() {
      that.parentNode.Code.popIn();
    }, 10000);
    

    【讨论】:

    • 此外,当弹出窗口打开时,它会冻结事件表上的事件以防止触发。您不能使用 setTimeout 关闭窗口,因为您必须先单击关闭窗口,然后事件表上的项目才会继续执行。
    • 好的,但是没有其他方法可以创建自动关闭的弹出窗口吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多