如何在页面刷新时使用 Javascript 切换图像?
假设我有 2 张图片:
- 图片A.jpg
- 图片B.jpg
我想在页面刷新时在 locationA 和 locationB 切换这些图像。
模拟:
- Page Refresh #1
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
- Page Refresh #2
<img id='locationA' src='ImageB.jpg'>
<img id='locationB ' src='ImageA.jpg'>
- Page Refresh #3
<img id='locationA' src='ImageA.jpg'>
<img id='locationB ' src='ImageB.jpg'>
[更新#1]
我尝试了这个实现,但它不起作用。谁能告诉我这段代码有什么问题?
<html>
<head>
<script type="text/javascript">
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index) index = 0;
if(index==0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index==1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
</script>
</head>
<body>
<img id='locationA' src=''>
<img id='locationB' src=''>
</body>
</html>
[更新#2]
测试:
- FF 16.0.1 --> 工作!
- IE 8 --> 不起作用
这是代码:
<html>
<head>
<script type="text/javascript">
function switchImage()
{
var images = [];
images[0] = "I_am_Super_Magnet%21.jpg";
images[1] = "World_In_My_Hand%21.jpg";
var index = sessionStorage.getItem('index');
if(index == null) index = 0;//set index to zero if null
index = parseInt(index);// parse index to integer, because sessionStorage.getItem() return string data type.
if(index == 0)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index+1];
index = index + 1;
}
else if(index == 1)
{
document.getElementById("locationA").src=images[index];
document.getElementById("locationB").src=images[index-1];
index = index - 1;
}
sessionStorage.setItem('index', index);
}
</script>
</head>
<body onload="switchImage()">
<img id='locationA' src='src_locationA'>
<img id='locationB' src='src_locationB'>
</body>
</html>
感谢杰克提供线索!感谢Jon Kartago Lamida提供的样品!
谢谢。