我有一个 link返回类似于以下图像的图像数组。
{ "imageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x50.png",
"expandedImageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x320.jpg" }
我的目标是在 <div>
中显示第一张图片,当它被点击时,它会变成第二张图片。
我怎样才能仅使用 HTML 和 JavaScript 实现这一点?
最佳答案
在普通的 javascript 中,假设您已经有一个声明为 <div id=divId></div>
的 div :
var images = {
"imageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x50.png",
"expandedImageUrl":"http://server06.amobee.com/aspx/nadav/test/banner320x320.jpg"
};
var div = document.getElementById('divId');
var img = document.createElement('img');
img.setAttribute('src', images.imageUrl);
div.appendChild(img);
img.onclick=function(){
this.src=images.expandedImageUrl;
};
如果你有一个类似于 images
的对象数组对象,您可以循环创建它们。由于“封闭效应”,它不像看起来那么微不足道,这就是我包含代码的原因:
var images = [
{ "imageUrl":"http://dystroy.org/re7210/img/crevettes-ail-courgettes-2-750.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/crevettes-ail-courgettes-750.jpg"},
{ "imageUrl":"http://dystroy.org/re7210/img/cote-beuf-champis-02-850.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/cote-beuf-champis-05-850.jpg"},
{ "imageUrl":"http://dystroy.org/re7210/img/onglet-truffes-850-02.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/onglet-truffes-850-05.jpg"}
];
var div = document.getElementById('divId');
for (var i=0; i<images.length; i++) {
var image =images[i];
var img = document.createElement('img');
img.setAttribute('src', image.imageUrl);
div.appendChild(img);
(function(expandedImageUrl){ // we embed the expanded URL in a closure to avoid having the value at end of loop used
img.onclick=function(){
this.src=expandedImageUrl;
};
})(image.expandedImageUrl);
}
在评论中编辑以下问题:
这是一个允许点击在两个图像之间切换的版本:
var images = [
{ "imageUrl":"http://dystroy.org/re7210/img/crevettes-ail-courgettes-2-750.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/crevettes-ail-courgettes-750.jpg"},
{ "imageUrl":"http://dystroy.org/re7210/img/cote-beuf-champis-02-850.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/cote-beuf-champis-05-850.jpg"},
{ "imageUrl":"http://dystroy.org/re7210/img/onglet-truffes-850-02.jpg",
"expandedImageUrl":"http://dystroy.org/re7210/img/onglet-truffes-850-05.jpg"}
];
var div = document.getElementById('divId');
for (var i=0; i<images.length; i++) {
var image =images[i];
var img = document.createElement('img');
img.setAttribute('src', image.imageUrl);
img.setAttribute('othersrc', image.expandedImageUrl);
img.setAttribute('width', '600px');
div.appendChild(img);
img.onclick=function(){
var src = this.getAttribute('src');
this.src = this.getAttribute('othersrc');
this.setAttribute('othersrc', src);
};
}
关于javascript - 将带有json的img数组放入div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12997607/