给5张图片,实现每点击一次有序或随机换一张图片的功能
有序
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>单击切换图片</title>
<script type="text/javascript">
var id = 1;
function next(){
id = (id+1) % 6; //1到5一直循环
if(id != 0){ //求余出现0的情况
document.getElementById("image").src =id + '.jpg';
}else{
id++;
document.getElementById("image").src =id + '.jpg';
}
}
</script>
</head>
<body>
<img id="image" width=426 height=130 οnclick='next()' src='1.jpg' />
</body>
</html>
随机版
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>单击切换图片</title>
<script type="text/javascript">
var id = 1;
function next(){
var id=Math.floor(Math.random()*5+1); //floor取整 如果直接写*6,会出现id=0的情况
document.getElementById("image").src =id + '.jpg';
}
</script>
</head>
<body>
<img id="image" width=426 height=130 οnclick='next()' src='1.jpg' />
</body>
</html>
随机带开始暂停,这个是别人的,可以再优化下
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
</head>
<body>
<div>
<img src="1.jpg"/><br/>
<input type="button" value="随机更换"/>
<input type="button" value="暂停"/>
</div>
<script type="text/javascript">
//创建一个数组
var paths = new Array();
var isExecute = true;
var count=0;
window.onload = function(){
//将N张图片的路径放入数组中
paths[0]="1.jpg";
paths[1]="2.jpg";
paths[2]="3.jpg";
paths[3]="4.jpg";
paths[4]="5.jpg";
}
//随机选择
document.getElementsByTagName("input")[0].οnclick=function(){
window.setInterval("changeImage()",1000);
isExecute=true;
}
//换图片
function changeImage(){
if(isExecute){
//随机选取一张图片
var path = getPath();
//动态修改图片的src属性值
var imgElement = document.images[0];
imgElement.src = path;
}
}
//随机选中一张图片的路径
function getPath(){
//随机获取0,1,2中的任何一个型值
var index = Math.floor(Math.random()*5);
count = count + 1 > 4 ? 0 : count+1;
return paths[count];
//return paths[index];
}
//暂停
document.getElementsByTagName("input")[1].οnclick=function(){
isExecute = false;
}
</script>
</body>
</html>
最后再写一个鼠标触发事件随机版,每进出一次图片区域即随机换一张图片,稍微改一下就行了
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script LANGUAGE="JavaScript">
function next(){
var id=Math.floor(Math.random()*5+1); //floor取整 如果直接写*6,会出现id=0的情况
document.getElementById("image").src =id + '.jpg';
}
</script>
</head>
<body>
<img id="image" onMouseOver="next()" src="1.jpg" />
</body>
</html>