简体   繁体   中英

How can i get continuous image marquee effect in javascript?

I am using this HTML code to get marquee effect, but there is gap between first and last image. How can i remove this white space to get continuous marquee effect using javascript.

 var Obj = null; var animate ; function init(){ Obj = document.getElementById('mover'); Obj.style.position= 'relative'; Obj.style.left = '-600px'; } function moveRight(){ Obj.style.left = parseInt(Obj.style.left) + 1 + 'px'; animate = setTimeout(moveRight,20); if(parseInt(Obj.style.left)>800) Obj.style.left = '-600px'; } function stop(){ clearTimeout(animate); Obj.style.left = '-600px'; } window.onload =init; 
 #wrapper { width:800px; overflow: hidden; } #mover{ width:10000px; overflow: hidden; } img{ padding: 0px; margin: -2px; display: inline; } 
 <html> <head> <title>JavaScript Animation</title> </head> <body> <form> <div id="wrapper"> <div id="mover"> <img id="myImage" src="http://lorempixel.com/g/200/150/cats/1" width="200" height="150" /> <img id="myImage" src="http://lorempixel.com/g/200/150/cats/2" width="200" height="150" /> <img id="myImage" src="http://lorempixel.com/g/200/150/cats/3" width="200" height="150" /> </div> </div> <p>Click the buttons below to handle animation</p> <input type="button" value="Start" onclick="moveRight();" /> <input type="button" value="Stop" onclick="stop();" /> </form> </body> </html> 

Also, if there is any other method for doing this task more efficiently, please do tell.

This is a consequence of using display: inline with your images -- all whitespace becomes visible, including the newlines between your images.

There are three good solutions. The first is to remove the newlines between your images in the HTML, although this may not be desirable or practical:

<div id="mover"><img id="myImage" src="images/building3.jpg" width="330" height="150"><img id="myImage" src="images/building5.jpg" width="330" height="150"><img id="myImage" src="images/building2.jpg" width="330" height="150"></div>

Second, since you're just viewing images, you can add:

#mover { font-size: 0; }

Which will eliminate the whitespace by flattening it to nothing. But if you might add text along with the images later, it will also be flattened to nothing, and you'll have to explicitly set it to a larger font again.


Or third, you can use floats instead:

#mover { overflow: auto; }
#mover img { float: left; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM