javascript 动态加载图片到 Div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13061539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading Images into Div Dynamically
提问by user200261
I have a list of profile images which appear in a "menu drop down" div which is initially hidden via CSS. I would like to load these images dynamically (as a list) when each menu item is selected, so as to reduce the page loading time. How is this possible?
我有一个显示在“菜单下拉”div 中的个人资料图像列表,该 div 最初通过 CSS 隐藏。我想在选择每个菜单项时动态加载这些图像(作为列表),以减少页面加载时间。这怎么可能?
回答by Nevin
Try to use:
尝试使用:
$("#divID").html("<img style='position:absolute' src='path/to/the/ajax_loader.gif'>");
If you using ajax:
如果您使用 ajax:
function sendAjax()
{
$("#divID").html("<img style='position:absolute' src='path/to/the/ajax_loader.gif'>");
// you ajax code
$("#divID").html(ajaxResponse);
}
you can also use document.getElementById('divID').innerHTML
instead of $("#divID").html()
. its also work fine
你也可以使用document.getElementById('divID').innerHTML
代替$("#divID").html()
。它也工作正常
If you use this method, doesn't need to hide the div using css. its automatically remove after the ajax response.
如果使用此方法,则不需要使用 css 隐藏 div。它在 ajax 响应后自动删除。
回答by Hussain Akhtar Wahid 'Ghouri'
Well, you can try this:
嗯,你可以试试这个:
<div id="desiredDiv">
</div>
<script>
var images = [
'http://www.example.com/img/image1.png',
'http://www.example.com/img/image2.png',
'http://www.example.com/img/image3.png',
...
];
for(var i=0; i<images.length; i++) {
$('#desiredDiv').append('<img src="'+images[i]+'" alt="" />');
}
</script>
回答by Mouad Debbar
You can keep the list of images in a JavaScript variable:
您可以将图像列表保存在 JavaScript 变量中:
var images = [
'http://www.example.com/img/image1.png',
'http://www.example.com/img/image2.png',
'http://www.example.com/img/image3.png',
...
];
Then you can load the image whenever you need by creating the image tag:
然后您可以通过创建图像标签随时加载图像:
var i = 0; // the index of the image in the list
var $img = $( '<img>' ).attr({'src':images[i]});
Just append the image to your div and it will be loaded automatically by the browser.
只需将图像附加到您的 div 中,浏览器就会自动加载它。
回答by Doug
In your HTML leave out the src attribute on each image tag. Instead, add an attribute called data-src and give it the image url.
在您的 HTML 中,省略每个图像标签上的 src 属性。相反,添加一个名为 data-src 的属性并为其提供图像 url。
Then, when the menu is displayed, run the following script:
然后,当菜单显示时,运行以下脚本:
$('.menu-class img').each(function() {
$(this).attr('src', $(this).data('src'));
});
Said script requires jquery if you don't already have it
如果您还没有该脚本,则该脚本需要 jquery