如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
如何向元素添加onload事件?
我可以使用:
<div onload="oQuickReply.swap();" ></div>
对于这个吗?
当前回答
你不能在div上添加事件onload,但你可以在文档加载时添加onkeydown并触发onkeydown事件
$(函数() { $(“.ccsdvCotentPS”).trigger(“onkeydown”); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js”></script> <div onkeydown=“setCss( );”> </div>'
其他回答
首先回答你的问题:不,你不能,不能直接这样做,就像你想做的那样。 也许现在回答有点晚,但这是我的解决方案,没有jQuery,纯javascript。 它最初是用来在DOM加载后和在keyup上应用一个调整文本区域大小的函数。
同样地,你可以用它来做一些(所有)div或只有一个,如果指定的话,像这样:
document.addEventListener("DOMContentLoaded", function() {
var divs = document.querySelectorAll('div'); // all divs
var mydiv = document.getElementById('myDiv'); // only div#myDiv
divs.forEach( div => {
do_something_with_all_divs(div);
});
do_something_with_mydiv(mydiv);
});
如果你真的需要在DOM加载后加载div,例如在ajax调用之后,你可以使用一个非常有用的hack,这很容易理解,你会发现它…working with-elements-before-the- DOM -is-ready....它说“在DOM准备好之前”,但它以同样的方式出色地工作,在ajax插入或js- appendchild -任何div之后。下面是代码,根据我的需要做了一些小更改。
css
.loaded { // I use only class loaded instead of a nodename
animation-name: nodeReady;
animation-duration: 0.001s;
}
@keyframes nodeReady {
from { clip: rect(1px, auto, auto, auto); }
to { clip: rect(0px, auto, auto, auto); }
}
javascript
document.addEventListener("animationstart", function(event) {
var e = event || window.event;
if (e.animationName == "nodeReady") {
e.target.classList.remove('loaded');
do_something_else();
}
}, false);
我有同样的问题,并试图让一个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.
我非常喜欢用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
这是一个非常简单的解决方案,100%有效。 在div中加载所有数据后,如果你想要执行javascript,只需在div或div的最后一行中加载<img>标记。 因为<img>标签支持onload事件,所以你可以很容易地调用javascript在这里如下:
<div>
<img onLoad="alert('Problem Solved');" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" />
</div>
上图只显示了一个点(.),你甚至无法正常看到。 试一试。
onload事件只能用于文档(主体)本身、帧、图像和脚本。换句话说,它只能附加到主体和/或每个外部资源。div不是外部资源,它是作为主体的一部分加载的,所以onload事件在那里不适用。