如何向元素添加onload事件?

我可以使用:

<div onload="oQuickReply.swap();" ></div>

对于这个吗?


当前回答

我有同样的问题,并试图让一个Div加载一个滚动脚本,使用onload或load。我发现的问题是,它总是在Div打开之前工作,而不是在Div打开期间或之后,所以它不会真正工作。

然后我想出了这个方法。

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);" 
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.

其他回答

如前所述,你不能在DIV上使用onLoad事件,而是在body标签之前使用它。

但如果你有一个页脚文件,并将其包含在许多页面中。最好先检查你想要的div是否在显示的页面上,这样代码就不会在不包含该div的页面上执行,从而加快加载速度并为应用程序节省一些时间。

所以你需要给那个DIV一个ID,然后做:

var myElem = document.getElementById('myElementId');
if (myElem !== null){ put your code here}

onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。

我非常喜欢用YUI3库来做这类事情。

<div id="mydiv"> ... </div>

<script>
YUI().use('node-base', function(Y) {
  Y.on("available", someFunction, '#mydiv')
})

见:http://developer.yahoo.com/yui/3/event/ onavailable

由于onload事件仅在少数元素上受支持,因此必须使用另一种方法。

你可以使用MutationObserver:

const trackElement = element => { let present = false; const checkIfPresent = () => { if (document.body.contains(element)) { if (!present) { console.log('in DOM:', element); } present = true; } else if (present) { present = false; console.log('Not in DOM'); } }; const observer = new MutationObserver(checkIfPresent); observer.observe(document.body, { childList: true }); checkIfPresent(); return observer; }; const element = document.querySelector('#element'); const add = () => document.body.appendChild(element); const remove = () => element.remove(); trackElement(element); <button onclick="add()">Add</button> <button onclick="remove()">Remove</button> <div id="element">Element</div>

Onload事件,它只支持下面列出的几个标签。

<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

这里是onload事件的引用