我将此代码从图像1更改为图像2.如何将其从图像2更改为图像3,然后再更改为图像1?感谢
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()"><img id="myImg" src="image1.gif" width="107" height="98"></button>
<script>
function myFunction()
{
document.getElementById("myImg").src="image2.gif";
}
</script>
</body>
</html>
答案 0 :(得分:2)
var img_array = ['http://placehold.it/100x100/green', 'http://placehold.it/100x100/blue', 'http://placehold.it/100x100/red'];
i = 0;
function myFunction() {
i++;
document.getElementById("myImg").src = img_array[i];
if (i == img_array.length - 1) {
i = -1;
}
}
答案 1 :(得分:1)
你可以做到
function myFunction()
{
if( document.getElementById("myImg").src == "image1.gif" ){
document.getElementById("myImg").src = "image2.gif";
}
elseif( document.getElementById("myImg").src == "image2.gif" ){
document.getElementById("myImg").src = "image3.gif";
}
else{
document.getElementById("myImg").src = "image1.gif";
}
}
它不是很优雅,但它可能是一种解决方案。
亲切的问候。
答案 2 :(得分:0)
将您的HTML更改为某种类型:
<button id="change-img"><img ... /></button>
然后,您可以向#change-img
元素添加onclick。在你的jQuery中,添加
$('#change-img').click(function() {
var image = $('#myImg');
var imgNum = image.attr('src').split('.')[0].replace('image', ''); // gets the number
imgNum = (imgNum % 3) + 1;
image.attr( { 'src' : 'image' + imgNum + '.gif' } ); // selects image, changes source
});
你有它。
制作了一个类似于您想要实现的演示:http://jsfiddle.net/94VKa/。
答案 3 :(得分:0)
另一种方法:
// initialise the array, using array-literal syntax:
var img_array = ['http://placehold.it/100x100/green',
'http://placehold.it/100x100/blue',
'http://placehold.it/100x100/red'];
function myFunction() {
// finding where in the 'img_array' the current src is to be found:
var current = img_array.indexOf(this.src);
// updating the src of the clicked element, to either the next element in
// the array (if 'current + 1' does *not* evaluate to equal the length of the
// array, or to the first element in the array if 'current + 1' *does* equal
// the length of the array:
this.src = img_array[current + 1 === img_array.length ? 0 : current + 1];
}
// getting a reference to the element to click on,
// add an event-listener to 'listen' for that event, and execute the
// named function:
document.getElementById('myImg').addEventListener('click', myFunction);
参考文献: