js怎么实现自动更换图片

JavaScript09

js怎么实现自动更换图片,第1张

自动更换图片,这个是用定时器做的。下面是简单的代码,仅供参考:

<style>    

*{ margin:0 padding:0 list-style:none}    

#box{ width:840px border:1px solid #000 height:210px margin:30px auto position:relative overflow:hidden}    

#box ul{ position:absolute left:0 top:0}    

#box ul li{ width:200px height:200px float:left padding:5px}    

</style>    

<script>    

window.onload=function(){    

var oBox=document.getElementById('box')    

var oUl=oBox.children[0]    

var aLi=oUl.children    

    

//复制一份内容    

oUl.innerHTML+=oUl.innerHTML    

oUl.style.width=aLi.length*aLi[0].offsetWidth+'px'    

    

setInterval(function(){    

var l=oUl.offsetLeft+10    

if(l>=0){    

l=-oUl.offsetWidth/2    

}    

oUl.style.left=l+'px'    

},30)    

}    

</script>    

</head>    

<body>    

<div id="box">    

<ul>    

    <li><img src="img/1.jpg" width="200"></li>    

       <li><img src="img/2.jpg" width="200"></li>    

       <li><img src="img/3.jpg" width="200"></li>    

       <li><img src="img/4.jpg" width="200"></li>    

           

   </ul>    

</div>

简单的说一下定时器:

setInterval定义和用法

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

语法

setInterval(code,millisec[,"lang"])

参数

code    必需。要调用的函数或要执行的代码串。  

millisec    必须。周期性执行或调用 code 之间的时间间隔,以毫秒计。

js版和css版自动按比例调整图片大小方法,分别如下:

<title>javascript图片大小处理函数</title>

<script language=Javascript>

var proMaxHeight = 150

var proMaxWidth = 110

function proDownImage(ImgD){

      var image=new Image()

      image.src=ImgD.src

      if(image.width>0 && image.height>0){

      var rate = (proMaxWidth/image.width < proMaxHeight/image.height)?proMaxWidth/image.width:proMaxHeight/image.height

    if(rate <= 1){   

     ImgD.width = image.width*rate

     ImgD.height =image.height*rate

    }

    else {

                          ImgD.width = image.width

                          ImgD.height =image.height

                  }

      }

}

</script>

</head>

<body>

<img src="999.jpg" border=0 width="150" height="110"  onload=proDownImage(this)   />

<img src="room.jpg" border=0 width="150" height="110" onload=proDownImage(this)   />

</body>

纯css的防止图片撑破页面的代码,图片会自动按比例缩小:

<style type="text/css">

.content-width {MARGIN: autoWIDTH: 600px}

.content-width img{MAX-WIDTH: 100%!importantHEIGHT: auto!importantwidth:expression(this.width > 600 ? "600px" : this.width)!important}

</style>

<div class="content-width">

  <p><img src="/down/js/images/12567247980.jpg"/></p>

  <p><img src="/down/js/images/12567247981.jpg"/></p>

</div>

把所有的图片的名字包括路径保存在数组中,通过Settimeout方法每次向下读取,document.getElementById("这里是Img的ID").src=img[i]i初始化为0,方法体内每次判断i是否到了数组下界,如果到了最后一张,在初始化为0,否则就i++