前端js基础效果--无缝滚动
直接上代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>无缝滚动 demo</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
list-style: none;
}
h1 {
text-align: center;
padding-top: 20px;
}
#box {
position: relative;
overflow: hidden;
width: 80%;
margin: 20px auto;
border: 2px solid #ccc;
}
#box ul {
position: relative;
left: 0;
width: 100%;
*zoom: 1;
box-sizing: border-box;
}
#box ul:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
#box ul li {
float: left;
width: 20%;
height: 200px;
padding: 20px;
box-sizing: border-box;
}
#box ul li:nth-child(1) {
background: red;
}
#box ul li:nth-child(2) {
background: orange;
}
#box ul li:nth-child(3) {
background: yellow;
}
#box ul li:nth-child(4) {
background: green;
}
#box ul li:nth-child(5) {
background: darkmagenta;
}
</style>
</head>
<body>
<h1>无缝滚动 demo</h1>
<div id="box">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<script type="text/javascript">
window.onload = function() {
run()
}
function run() {
//找到对应的元素
var box = document.getElementById('box');
var ul = box.getElementsByTagName('ul')[0];
var lis = ul.getElementsByTagName('li');
//定义移动距离
let speed = 1;
//获取 li 的宽度
let liWidth = lis[0].offsetWidth;
//获取 li 的高度
let liHeight = lis[0].offsetHeight;
//设置 盒子(box)的高度
box.style.height = liHeight + 'px';
//以px为单位设置li的宽度(若在css中已经设置 可忽略 这里我用百分比布局所以需要重新赋值)
for(let i = 0; i < lis.length; i++) {
lis[i].style.width = liWidth + 'px';
//复制背景颜色
lis[i].style.background = getBg(lis[i]);
}
//复制ul内容并且ul的宽度也要增加
ul.innerHTML += ul.innerHTML;
ul.style.width = lis.length * liWidth + 'px';
//判断移动距离
function move() {
//左侧距离小于负的 ul总宽度的二分之一 则让ul返回距离左侧为0 的位置
if(ul.offsetLeft < -ul.offsetWidth / 2) {
ul.style.left = '0';
}
//如果大于等于0 则设置到 距左侧 为ul宽度一半的位置
if(ul.offsetLeft >= 0) {
ul.style.left = -ul.offsetWidth / 2 + 'px';
}
//每次移动的距离
ul.style.left = ul.offsetLeft + speed + 'px';
}
//启动计时器 每15毫秒执行一次
let timer = setInterval(move, 15);
//鼠标经过停止滚动 清除计时器
box.onmouseover = function() {
clearInterval(timer);
}
//鼠标移出 开始滚动
box.onmouseout = function() {
timer = setInterval(move, 15);
}
}
//获取背景颜色方法
function getBg(element) {
cssProperty = "backgroundColor";
mozillaEquivalentCSS = "background-color";
if(element.currentStyle)
var actualColor = element.currentStyle[cssProperty];
else {
var cs = document.defaultView.getComputedStyle(element, null);
var actualColor = cs.getPropertyValue(mozillaEquivalentCSS);
}
if(actualColor == "transparent" && element.parentNode)
return arguments.callee(element.parentNode);
if(actualColor == null)
return "#ffffff";
else
return actualColor;
}
</script>
</body>
</html>