In this article, we implement the rolling advertising effect in pure JS for your reference. The specific content is as follows
Let’s show the finished product first:
The first is the web page style:
#demo { background: #FFF; overflow:hidden; border: 1px dashed #CCC; width: 1280px; height:200px; } #demo img { border: 3px solid #F2F2F2; } #indemo { float: left; width: 800%; } #demo1 { float: left; } #demo2 { float: left; }
The layout is as follows:
<div id="demo"> <div id="indemo"> <div id="demo1"> <a href="#"><img src="banner.jpg" border="0" /></a> <a href="#"><img src="banner2.jpg" border="0" /></a> </div> <div id="demo2"></div> </div> </div>
Specific JS implementation:
<script> var speed=10; var tab=document.getElementById("demo"); var tab1=document.getElementById("demo1"); var tab2=document.getElementById("demo2"); tab2.innerHTML=tab1.innerHTML; function Marquee(){ if(tab2.offsetWidth-tab.scrollLeft==0) tab.scrollLeft-=tab1.offsetWidth else{ tab.scrollLeft++; } } var MyMar=setInterval(Marquee,speed); tab.onmouseover=function() {clearInterval(MyMar)}; tab.onmouseout=function() {MyMar=setInterval (Marquee,speed)}; </script>
What should be noted here is:
scrollLeft represents the width of the page hidden on the left side of the scroll bar when the page is scrolled to the right using the scroll bar.
offsetWidth is the visible width of the object, including scroll bars and other edges, which will change with the display size of the window.
setInterval() method can call a function or calculate an expression according to the specified period (in milliseconds). The setInterval() method will continue to call the function until clearInterval() is called or the window is closed.
It will be easier to understand once you understand the specific implementation.
The implementation principle is as follows: first copy the content that needs to be scrolled. When the content displayed by the right div is the same as the content of the left shadow, the content of the shadow on the left side of the parent container is displayed. In this way, the content of the left shadow is displayed and the content on the right is re-hidden. . If the content displayed on the right is less than the content hidden on the left, the parent container will continue to be moved to the left to hide it. One thing to note is that since the two pictures are placed on the left side at the same time, when half of the right side is displayed, the hidden shadow on the left side will be fully displayed, and because the content displayed on the right side is different from the content on the left side. The content on the left is the same, so the effect of circular scrolling is achieved.
Smooth scrolling is achieved in this way.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.