使用JS附加body onload事件

如何通过跨浏览器方式将主体onload事件与JS关联?这样简单吗?


  document.body.onload = function(){

      alert("LOADED!");

  }


红颜莎娜
浏览 580回答 3
3回答

胡子哥哥

这利用了DOMContentLoaded的优点-在onload之前会触发-但允许您坚持所有不引人注意的内容...window.onload-Dean Edwards-该博客文章讨论了更多内容-这是从同一博客的评论中复制的完整代码。// Dean Edwards/Matthias Miller/John Resigfunction init() {&nbsp; // quit if this function has already been called&nbsp; if (arguments.callee.done) return;&nbsp; // flag this function so we don't do the same thing twice&nbsp; arguments.callee.done = true;&nbsp; // kill the timer&nbsp; if (_timer) clearInterval(_timer);&nbsp; // do stuff};/* for Mozilla/Opera9 */if (document.addEventListener) {&nbsp; document.addEventListener("DOMContentLoaded", init, false);}/* for Internet Explorer *//*@cc_on @*//*@if (@_win32)&nbsp; document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");&nbsp; var script = document.getElementById("__ie_onload");&nbsp; script.onreadystatechange = function() {&nbsp; &nbsp; if (this.readyState == "complete") {&nbsp; &nbsp; &nbsp; init(); // call the onload handler&nbsp; &nbsp; }&nbsp; };/*@end @*//* for Safari */if (/WebKit/i.test(navigator.userAgent)) { // sniff&nbsp; var _timer = setInterval(function() {&nbsp; &nbsp; if (/loaded|complete/.test(document.readyState)) {&nbsp; &nbsp; &nbsp; init(); // call the onload handler&nbsp; &nbsp; }&nbsp; }, 10);}/* for other browsers */window.onload = init;

吃鸡游戏

为什么不使用window自己的onload事件?window.onload = function () {&nbsp; &nbsp; &nbsp; alert("LOADED!");}如果我没记错的话,那么所有浏览器都兼容。

ITMISS

jcalfee314的想法对我有用-我有一个window.onload = onLoad含义,即其中的函数<body onload="...">没有被调用(我无法控制)。这修复了它:oldOnLoad = window.onloadwindow.onload = onLoad;function onLoad(){oldOnLoad();...}编辑:Firefox不喜欢oldOnLoad = document.body.onload;,所以替换为oldOnLoad = window.onload。
打开App,查看更多内容
随时随地看视频慕课网APP