网页窗口关闭前进行提示(适用于IE和FF, 标题栏的X关闭按钮)

    技术2022-05-19  24

    function getEvent() //同时兼容ie和ff的写法, 这个方法是网上copy的     {        if(document.all)   return window.event;        func=getEvent.caller;        while(func!=null){            var arg0=func.arguments[0];            if(arg0)            {                if((arg0.constructor==Event || arg0.constructor ==MouseEvent) || (typeof(arg0)=="object" && arg0.preventDefault && arg0.stopPropagation))                {                    return arg0;                }            }            func=func.caller;        }        return null;    }    function ConfirmClose() {        if(window.event)            window.event.returnValue = "在关闭窗口前确认您是否已经保存了信息!";        else            getEvent().preventDefault();//for firefox    }    function on_page_loaded()   //自己定义的body的onload事件     {        try{            if(!window.onbeforeunload )    //为了不覆盖原来的onbeforeunload方法,先判断                window.onbeforeunload = ConfirmClose;   //todo 增加了窗口关闭前的提示        }catch(e){}    }

    这个主要是在页面定义一个在关闭或更新页面文档文档前的事件(onbeforeunload 

    兼容IE和FF,

    重点: 

    IE:event.returnValue如果设置了该属性,它的值比事件句柄的返回值优先级高。把这个属性设置为 fasle,可以取消发生事件的源元素的默认动作。

     

    FF:e.preventDefault()方法作用跟上面一样 

     

    说白了,利用这两个可以在事件发生前弹出提示框阻止事件和让事件继续进行,如onclick, onkeydown, onfocus, close 等事件

     

    对于IE还可以用

    function on_page_loaded(){         try{

                if(!document.body.onbeforeunload ) 

                    document.body.onbeforeunload =function(){ConfirmClose();};   //todo 增加了窗口关闭前的提示        }catch(e){}

    }

    这个主要是document.body 和 window的区别, 上面这个方法在FF是不起作用的, 虽然定义了body的onbeforeunload 事件,但是没有效果。

     但你直接<body onbeforeunload = ConfirmClose();> 在 IE 和 FF 是可以的(很奇怪,希望有人能解释下)

    PS. 不要把自定义的属性加到document对象上,这会使得每次读取该属性时进行额外的重算。推荐加在window对象上

    查了一些资料发现原来还可以更简单的

    function ConfirmClose() {        return "在关闭窗口前确认您是否已经保存了信息!";    }

    function on_page_loaded()    {         try{            if(!window.onbeforeunload)                window.onbeforeunload = function(){return ConfirmClose();};   //todo 增加了窗口关闭前的提示        }catch(e){}    }

    这个够简单了吧 

     

    -------------------------------------------------

    以上在IE6和firefox 2.0测试通过


    最新回复(0)