我建议类似于以下内容:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum).src;
}
else {
var next = document.getElementById(nextElemId).src;
}
elem.src = next;
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}
JS 小提琴演示。
编辑补充说,虽然可以切换src
图像的属性,但似乎没有必要,因为这两个图像都存在于 DOM 中。另一种方法是简单地隐藏单击的图像并显示下一个:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}
JS 小提琴演示。
编辑以提供另一种方法,将元素移动next
到与单击的图像元素相同的位置:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.parentNode.insertBefore(next,elem.nextSibling);
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}
JS 小提琴演示。