Home > Article > Web Front-end > How to implement image scrolling with JavaScript
JavaScript method to implement image scrolling: [<script>var timer;var speed=10;var box=document.getElementById("box");var boxin=document.getEl...]. </script>
#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.
Let’s first take a look at the principle of achieving the image scrolling effect:
The black box is the area where the scrolling image is finally displayed, and the green box is its sub-container. Its width must be larger than the black outer box, so that the image can be scrolled by setting the scrollLeft of the black box. The innermost blue box is used to wrap all scrolled images, while the contents of the purple box will be the same as the blue box in the future to enable seamless image scrolling. Use the JS timer to change the value of the scrollLeft attribute of the black box at regular intervals to scroll the image to the left. At the same time, determine the value of scrollLeft. If its value reaches the rightmost side of the black box container, it means that the blue box The black box has been scrolled to the left, and the purple box is just inside the black box. At this time, you need to set the scrollLeft value of the black box to 0 and start again.
Specific implementation code:
html code:
<!\-\- 最外层盒子 --\> <div id="box"> <div id="boxin"> <div id="neirong"> <img src="Images/C_2.jpg" alt=""> <img src="Images/C_3.jpg" alt=""> <img src="Images/C_4.jpg" alt=""> <img src="Images/C_5.jpg" alt=""> <img src="Images/C_6.jpg" alt=""> </div> <div id="neirong2"></div> </div> </div>
css code:
*{ margin: 0; padding: 0; } #box{ height: 100px; width: 500px; overflow: hidden; } #boxin{ width: 1064px; height: 100px; } #neirong{ float: left; } #neirong2{ float: left; } img{ width: 100px; height: 100px; } </style>
js code:
<script> var timer; var speed=10; var box=document.getElementById("box"); var boxin=document.getElementById("boxin"); var neirong=document.getElementById("neirong"); var neirong2=document.getElementById("neirong2"); neirong2.innerHTML=neirong.innerHTML; function move(){ if(neirong2.scrollWidth-box.scrollLeft<=0){ box.scrollLeft=0; }else{ box.scrollLeft++; } } box.onmouseover=function(){ clearInterval(timer); } box.onmouseout=function(){ timer=setInterval(move,speed); } timer=setInterval(move,speed); </script>
Recommended learning: javascript video tutorial
The above is the detailed content of How to implement image scrolling with JavaScript. For more information, please follow other related articles on the PHP Chinese website!