我是根据:Controlling image load order in HTML
写的我更换了' src'改变' .attr'功能,它不能再回调。改变一次后停止了:
这一行:I.src = imgAddresses[counter];
进入:$("#page"+counter).attr("data-bgimage",imgAddresses[counter]);
HTML:
<div id="intro" class="slidingSpaces demo0" data-bgimage='' title="Intro">
<p>Hello</p>
<div id="page0" class="slidingSpaces demo0" data-bgimage='' title="Cover">
</div>
<div id="page1" class="slidingSpaces demo0" data-bgimage='' title="01">
</div>
<div id="page2" class="slidingSpaces demo0" data-bgimage='' title="02">
</div>
JS:
var imgAddresses = ['img1.png','img2.png','img3.png'];
function loadImage(counter) {
//Break out if no more images
if(counter==imgAddresses.length) { return; }
//Grab an image obj
var I = document.getElementById("page"+counter);
//Monitor load or error events, moving on to next image in either case
I.onload = I.onerror = function() { loadImage(counter+1); },
//Change source (then wait for event)
$("#page"+counter).attr("data-bgimage",imgAddresses[counter]);
}
loadImage(0);
注意:&#34; data-bgimage&#34;来自FerroSlider jQuery Plugin. div 必须将其用于背景图片。
答案 0 :(得分:0)
为什么不能正常工作
您无法在onload
元素上使用onerror
或<div>
。
onload事件只能用于以下元素
<body>
,<frame>
,<iframe>
,<img>
,<input type="image">
,<link>
,<script>
,<style>
...基本上包含外部资源的元素
<div>
不是外部资源,因为它是作为正文的一部分加载的,因此onload事件不适用于那里。
一些可能的解决方案
如果不了解您的全部要求和限制,我可以看到您可以
使用<img>
代码
循环调用loadImage()
功能。
for(var i=0; i < imgAddresses.length; i++) {
loadImage(i);
}
这可能有点矫枉过正,但您可以使用DOM Mutation Observers,每当dom更改时都会通知您
var imgAddresses = ['img1.png', 'img2.png', 'img3.png'];
var observers = [];
function loadImage(counter) {
//Break out and clean up if no more images
if (counter === imgAddresses.length) {
observers.forEach(function (observer) {
// later, you can stop observing
observer.disconnect();
});
//delete observers array
observers.splice(0, counter);
return;
}
var target = document.querySelector("#page" + counter);
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
console.log("page " + counter + " changed", mutation.target);
loadImage(counter + 1);
});
});
observers.push(observer);
// configuration of the observer:
var config = {
attributes: true, // monitoring attrs only
childList: false,
characterData: false
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
//Change attr (then wait for observer to pick up change)
$(target).attr("data-bgimage", imgAddresses[counter]);
}
loadImage(0);
答案 1 :(得分:0)
如果您正在尝试编辑data- *属性,则应使用.data()
var imgAddresses = ['img1.png', 'img2.png', 'img3.png'];
function loadImage(images) {
for(var i = 0; i < imgAddresses.length; i++){
$('#page' + i).data('bgimage', imgAddresses[i]);
}
}
loadImage(imgAddresses);