日期:2014-05-16  浏览次数:20416 次

求教:图片随机播放代码
1、网页每隔一段时间自动刷新,每次刷新出一张图片,图片要求随机出现;
2、用鼠标点击图片的任何一个位置停止刷新,再点一次又开始刷新,如此反复。

用js代码能做到吗?另外,如果刷新次数太多会不会占用过多的系统内存?如果会,应该如何解决呢?

------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
var arImgs = [
    'http://img5.cache.netease.com/cnews/2012/6/29/201206291228580c0ae.jpg',
    'http://img6.cache.netease.com/cnews/2012/6/30/201206301612199c584.jpg',
    'http://img1.cache.netease.com/cnews/2012/6/30/201206301334196ff3d.jpg',
    'http://img6.cache.netease.com/cnews/2012/6/30/20120630130449974bb.jpg',
    'http://img3.cache.netease.com/cnews/2012/6/30/201206301119029b4db.jpg'
], t, flagSTOP = false;

function showRandImg(ar) {
    document.getElementById('container').getElementsByTagName('img')[0].src = ar[Math.floor(Math.random() * (ar.length - 1))];
}
window.onload = function() {
    t = window.setInterval('showRandImg(arImgs)', 1000);
    
    var oImg = document.getElementById('container').getElementsByTagName('img')[0];
    oImg.onclick = function() {
        if (flagSTOP) window.setInterval('showRandImg(arImgs)', 1000);
        else {
            t = window.clearInterval(t);
            flagSTOP = true;
        }
    }
}
</script>
</head>

<body>
<div id="container"><img src="http://img3.cache.netease.com/cnews/2012/6/30/201206300956573145b.jpg" /></div>
</body>
</html>

------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
function Init(){
this.is=0;
this.time="";
this.images=[];
this.image=document.images[0];
this.image.onclick=this.isStop.bind(this);
this.images.push("1.jpg");
this.images.push("2.jpg");
this.images.push("3.jpg");
this.images.push("4.jpg");
this.change();
}
Init.prototype.change=function(){
var r=parseInt(Math.random()*(this.images.length+1));
this.image.src=this.images[r];
this.time=window.setTimeout(this.change.bind(this),1000);

Init.prototype.isStop=function(){
if(this.is==0){
window.clearTimeout(this.time);
this.is=1;
}else{
this.change();
this.is=0;
}
}
window.onload=function(){
new Init();
}
</script>
</head>

<body>
<img src="1.jpg">
</body>
</html>
这样试试