如何获取页面上所有图像的来源,然后将它们全部放在一个分区中

How to get sources of all images on page and then put them all in one division

本文关键字:全部 然后 分区 一个 获取 何获取 图像      更新时间:2023-09-26

我想要的是,在页面加载之前,它会获取页面上的所有图像,并将它们放入一个分区中。
例如。该页面有 5 张图片 - eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png.现在,在页面开始加载之前,所有图像都保留在页面中,但也要使用id'pre'进行划分。 我希望这是动态完成的,这样如果我更改页面上的图像,分区上的图像也会更改。
.HTML:-

<div id="content-wrapper">
     <img src="eg1.png">
     <img src="eg2.jpg">
     <img src="eg3.bmp">
     <img src="eg4.jpg">
     <img src="eg5.png">
</div>
<div id="pre">//all the images in 'content-wrapper' should also appear here//</div>  

我在div中放置了一个图像,该图像将"pre"设置为id:

$('img').each(function(){
  var src = $(this).attr('src');
  $('#pre').append("<img src='"+ src +"' /><br>");
});

但是当我更改src属性时:

$("img").one("load", function() {
    alert($(this).attr('src'));
});
这是

您的示例代码 http://jsfiddle.net/fpWWT/1/

和简单的jQuery函数,以满足您的需求

$('img').each(function(){
 var src = $(this).attr('src')+'<br>';
  $('#pre').append(src);
});

您可以做的是首先获取所有图像源,将其添加到数组中。然后将这些图像加载到缓存中,并在 prediv 中显示它们。在此之前,在 prediv 中显示某物的加载图像。并且还使部门内容包装器显示:无,以便用户看不到幕后发生的事情。这是代码

var $images = $("#content-wrapper img");
//in case you want to show progress bar
var $totalImages = $images.length;
//lets make a array to hold the images
var $imageHolder = []; 
//now lets add the images to cache
$images.each(function(i){
     var $img = new Image();
     $img.onload = function(){
           $imageHolder.push($img); 
           }
     $img.src = $(this).attr('src');
     });
//now that all your images are loaded into the cache add them to your div
$.each($imageHolder,function(i,item){
$("#pre").append(item);
});
//Done

这将是完全动态的,无论您在包装器div 中获得了多少图像。