js动态轮播图
效果分析:
-
自动向左移动播放图片
-
鼠标炫富在图片下端小圆点,被悬浮的小圆点变色,并且显示对应序号的图片
-
鼠标悬浮在图片上任意一处,在图片左右两边显示移动箭头,并且 让页面静止在本章图片上,当鼠标移出图片时,箭头消失,页面继续自动播放图片
-
点击图片左右箭头,图片分别向左向右滑动
效果图
js代码
onload=function(){
var scrren = myId("scrren");//相框
var imgWidth = scrren.offsetWidth;//相框的宽度
var ulObj = myId("uu");//ul
var list = myId("uu").getElementsByTagName("li");//所有的li的节点
var olObj = myId("oo");//ol
var btnBox = myId("arr");//左右两边按钮的盒子
//1.创建小按钮。 根据小按钮, 切换对应的图片
for(var i = 0 ; i < list.length; i++){
var liObj = document.createElement("li");
olObj.appendChild(liObj);
liObj.innerHTML = i + 1;
liObj.setAttribute("index", i);
liObj.onmouseover = function () {
//先干掉所有的li的背景颜色
// clearInterval(timerId);
for(var j = 0 ; j < olObj.children.length ; j++){
olObj.children[j].removeAttribute("class");
}
this.className = "current";
//获取对应的索引
var picIndex = this.getAttribute("index");
//移动ul
animateDong(ulObj, -picIndex * imgWidth);
}
}
//设置ol中第一个li默认有背景颜色
olObj.firstElementChild.className = "current";
//2.自动播放
//克隆一个ul的第一个图片, 添加到最后面去
ulObj.appendChild(ulObj.children[0].cloneNode(true));
//开定时器
var timerId = setInterval(move, 1000);
var index = 0;
//右键移动和小圆点移动的函数
function move() {
if(index >= list.length - 1){
//直接跳转到第一个图片
index = 0;
ulObj.style.left = "0px";
}
index++;
animateDong(ulObj, -index * imgWidth);
//判断图片对应的小圆点在显示对应的图片是否变色
if(index == list.length -1){
//把最后一个按钮颜色去掉
olObj.children[olObj.children.length - 1].className = "";
//给第一个按钮设置颜色
olObj.children[0].className = "current";
}else{
//先干掉所有的li的背景颜色
for(var j = 0 ; j < olObj.children.length ; j++){
olObj.children[j].removeAttribute("class");
}
olObj.children[index].className = "current";
}
}
//3.鼠标移入移出
myId("box").onmouseover = function () {
btnBox.style.display = "block";
clearInterval(timerId);
}
myId("box").onmouseout = function () {
btnBox.style.display = "none";
timerId = setInterval(move, 1000);
}
//4.点击两边按钮
//点击左边的按钮
myId("right").onclick = move;
//点击右边的按钮
myId("left").onclick = function () {
if(index == 0){
index = list.length - 1;
ulObj.style.left = -index * imgWidth + "px";
}
index--;
animateDong(ulObj, -index * imgWidth);
//先干掉所有的li的背景颜色
for(var j = 0 ; j < olObj.children.length ; j++){
olObj.children[j].removeAttribute("class");
}
olObj.children[index].className = "current";
}
}
封装的js函数common.js
//封装通过Id名获取元素
function myId(id){
return document.getElementById(id);
}
function myTN(element){
return document.getElementsByTagName(element);
}
//封装变速动画
function animateDong(element,target){
clearInterval(element.timeId);
element.timeId=setInterval(function(){
//获取当前元素的位置
var current=element.offsetLeft;
// console.log(current);
//设置移动的步数
var step=(target-current)/10;
step=step>0?Math.ceil(step):Math.floor(step);
//获取每次移动后的left值
current+=step;
element.style.left=current+"px";
if(current==target){
clearInterval(element.timeId);
}
// console.log("目标位置"+target+",每次移动的距离"+step+",当前位置"+current);
},10)
}
**
轮播图暂时完毕,如果有更新修改,敬请期待,谢谢观看!!!
**