首先,我的主要目的是在页面加载后加载图像。接下来,我不想在我的HTML代码中指定图像标记,因此我不需要提供任何src属性。
假设这是我的标签,它应该在页面加载后加载图像
<head>
<p title="image_source" style="height:100px;width:100px;"></p>
</head>
var imagetag = document.createElement('img');
window.addEventListener('load', function() {
for (var x=0; x < document.getElementsByTagName('p').length; x++) {
}
});
我个人会在加载后使用数据属性和类来向页面添加图像。
window.addEventListener("load", function () {
var imgs = document.querySelectorAll(".img_load")
imgs.forEach(function (el) {
var img = document.createElement("img");
img.src = el.dataset.src
el.appendChild(img);
});
});
<p class="img_load" data-src="http://via.placeholder.com/350x150" style="height:100px;width:100px;"></p>
<p class="img_load" data-src="http://via.placeholder.com/450x150" style="height:100px;width:100px;"></p>
<p class="img_load" data-src="http://via.placeholder.com/350x450" style="height:100px;width:100px;"></p>
此脚本在整个页面完成加载后加载所有图像
每个带有类img_load的#a标签都会通过将data-scr作为图像源来加载图像
<script>
window.addEventListener('load', function(){
var parent = document.getElementsByClassName('img_load');
for (var i = 0; i < parent.length; i++){
parent[i].appendChild(document.createElement('img')).setAttribute('src',
parent[i].getAttribute('data-src'));}})
</script>
<a class="img_load" data-src="image_source.png"
style="height:00px;width:100px;position:relative;"></a>
<a class="img_load" data-src="image_source.jpg"
style="height:100px;width:100px;position:relative;">b</a>