Javascript achieves seamless image scrolling and javascript seamless
Effect: move the mouse over the image to stop scrolling. Move the mouse over the image to automatically scroll.
You can adjust to scroll left or right
Copy codeThe Code is as follows:
<Style type = "text/css">
*{
Margin: 0;
Padding: 0;
}
# Div1 {
Overflow: hidden;
Width: 712px;
Height: pixel PX;
Margin: 100px auto;
Position: relative;
Background: red;
}
# Div1 ul {
Position: absolute;
Left: 0;
Top: 0;
}
# Div1 ul li {
Float: left;
Width: 178px;
Height: pixel PX;
List-style: none;
}
</Style>
Copy codeThe Code is as follows:
<Body>
<A href = "javascript:;"> left </a>
<A href = "javascript:;"> right </a>
<Div id = "div1">
<Ul>
<Li>
</Li>
<Li>
</Li>
<Li>
</Li>
<Li>
</Li>
</Ul>
</Div>
</Body>
The above is a simple layout, and the following is the main Javascript code
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Window. onload = function (){
Var oDiv = document. getElementById ("div1 ");
Var oUl = oDiv. getElementsByTagName ('ul ') [0];
Var aLi = oUl. getElementsByTagName ('lil ');
Var speed = 2;
OUl. innerHTML + = oUl. innerHTML;
OUl. style. width = aLi [0]. offsetWidth * aLi. length + 'px ';
Function move (){
If (oUl. offsetLeft <-oUl. offsetWidth/2 ){
OUl. style. left = '0 ';
}
If (oUl. offsetLeft> 0 ){
OUl. style. left =-oUl. offsetWidth/2 + 'px ';
}
OUl. style. left = oUl. offsetLeft + speed + 'px ';
}
Var timer = setInterval (move, 30 );
ODiv. onmouseover = function (){
ClearInterval (timer );
};
ODiv. onmouseout = function (){
Timer = setInterval (move, 30 );
};
Document. getElementsByTagName ('A') [0]. onclick = function (){
Speed =-2;
};
Document. getElementsByTagName ('A') [1]. onclick = function (){
Speed = 2;
};
}
</Script>
Briefly describe the following ideas:
First, set a total of eight oUl. innerHTML + = oUl. innerHTML images in ul;
When calculating the actual width of ul as li x 8
Then, hide the excess content.
Note: oUl. offsetLeft must be a negative value.
Therefore, do not miss the negative number during judgment.
Copy codeThe Code is as follows:
If (oUl. offsetLeft <-oUl. offsetWidth/2 ){
OUl. style. left = '0 ';
}
This section indicates that the image is rolled in half and the image is pulled back quickly. Because the program runs too fast, it is almost invisible to achieve seamless scrolling.
Finally, the variable speed is used to control the scrolling in the left and right directions.
The above Code only implements the most basic functions, and our friends can continue to improve it on this basis.