在纯 javascript 中,假设您已经有一个 div 声明为<div id=divId></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);
}
</p>
示范
在评论中编辑以下问题:
这是一个允许单击在两个图像之间切换的版本:
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);
};
}
示范