用简单的JS实现轮播的功能
开发工具与关键技术:JavaScript
作者:陈希雄
撰写时间:2019/2/14
主要是思路,如果思路不清晰的话,告诉你可能会写得一塌糊涂
HTML代码:
<div class="conten">
<div id="lb" style="width:4597px;position:absolute;left:0">
<img src="~/Content/壁纸包/1053344.jpg" />
<img src="~/Content/壁纸包/1013511.jpg" />
<img src="~/Content/壁纸包/1034558.jpg" />
<img src="~/Content/壁纸包/1037902.jpg" />
<img src="~/Content/壁纸包/1045546.jpg" />
<img src="~/Content/壁纸包/1053344.jpg" />
<img src="~/Content/壁纸包/1013511.jpg" />
</div>
</div>
CSS 代码:
#lb img{
width:650px;
height:400px;
}
.conten {
border: 1px solid #ccc;
width: 650px;
height: 400px;
position: relative;
overflow: hidden;
margin-left: 22%;
}
JS 代码
dc("lb");
function dc(id) {
Dp();
var left = 0; var s, t = 0;
var img = document.getElementById("" + id + "");
var offsetWidth = parseFloat(img.children[0].offsetWidth + 5);//获取当前这个div里面的img的宽
function Dp() {
s = setInterval(function () {
if (t <= -offsetWidth * (img.childElementCount - 2)) {//img.childElementCount 获取这个div里面所有子元素的数量
left = 0;
t = 0;
t -= offsetWidth;
Go();
} else {
t -= offsetWidth;
Go();
}
}, 2000);
}
function Go() {
if (left <= t) {
img.style.left = "" + t + "px";//防止div边缘出现间隙或者空白
clearInterval(s);
Dp();
} else {
img.style.left = "" + parseFloat(left -= 20) + "px";
setTimeout(Go, 10);//动画的速度
}
}
//设置鼠标的移入、移出事件来控制图片的播放、停止;
img.onmouseover = function () {
clearInterval(s);
};
img.onmouseout = function () {
Dp();
}
}
效果图:
来源:CSDN
作者:cxxone
链接:https://blog.csdn.net/weixin_44560342/article/details/87283695