轮播图滑动式基础篇

2019-05-22  本文已影响0人  深拥不及永伴i_e7df

轮播图常见的分为两种,一种是直接切换图片(这种方式使用的少),另外一种是切换的图片慢慢滑过去覆盖第一张图片(这种方式使用的多)。
今天要分享的是需要切换图片慢慢滑过去覆盖第一张照片,并且当鼠标移动到图片上时,图片不会发生切换操作,只有当鼠标移开时,图片继续慢慢滑动覆盖第一张照片。
话不多说我们上代码慢慢解读
由于本人比较懒>-<,没有找图片直接使用3个div代替,设置背景颜色,大家别见外哈。
附上代码:
首先我们创建一个div,取名为box,然后添加两个事件(一个当鼠标指针移动到图像上时执行一段 JavaScript事件,另外一个当鼠标指针移动到图像之外时执行一段 JavaScript事件)

<div id="box" onmouseover="stop()" onmouseout="start()">
    <div id="red" class="slide"></div>
    <div id="green" class="slide"></div>
    <div id="blue" class="slide"></div>
</div>

然后设置图像布局

#box{
    width:100px;
    height:100px;
    border:1px solid black;
    position:relative;
    overflow:hidden;
}
#red{
    background-color: red;
    width:100px;
}
#green{
    background-color: green;
    width:100px;
}
#blue{
    background-color: blue;
    width:100px;
}
.slide{
    width:100px;
    height:100px;
    position:absolute;
}

页面上只显示最后那个张“图片”,也没有自己轮播起来,不急这个时候我们需要添加js代码,使图片轮播起来并添加动作。
附全部代码如下:

 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="UTF-8">
 <title>轮播图</title>
 <style type="text/css">
  #box{
    width:100px;
    height:100px;
    border:1px solid black;
    position:relative;
    overflow:hidden;
  }
  #red{
    background-color: red;
    width:100px;
  }
  #green{
    background-color: green;
    width:100px;
  }
  #blue{
    background-color: blue;
    width:100px;
  }
  .slide{
    width:100px;
    height:100px;
    position:absolute;
  }
</style>
<script type="text/javascript">
// onload 事件会在页面或图像加载完成后立即发生。
onload=function(){
    var arr = document.getElementsByClassName("slide");
    for(var i=0;i<arr.length;i++){
        arr[i].style.left = i*100+"px";
    }
}
// 6执行LeftMove方法
function LeftMove(){
    var arr = document.getElementsByClassName("slide");// 获取三个子div
    for(var i=0;i<arr.length;i++){
        var left = parseFloat(arr[i].style.left);
        left-=2;
        var width = 100;// 图片的宽度
        if(left<=-width){
            left=(arr.length-1)*width;// 当图片完全走出显示框,拼接到末尾
            clearInterval(moveId);
        }
        arr[i].style.left = left+"px";
    }
}
// 5设置一个10毫秒定时器
function divInterval(){
    moveId=setInterval(LeftMove,10); 
}

// 4设置一个2秒的定时器
timeId=setInterval(divInterval,2000);


// 7页面失去焦点停止
onblur = function(){
    stop();
}

// 1页面获取焦点时开始
onfocus = function(){
    start();
}
// 8
function stop(){
    clearInterval(timeId);
}
// 2执行start方法
function start(){
    clearInterval(timeId); // 3设置一个2秒的定时器。 
    timeId=setInterval(divInterval,2000);
}
</script>
</head>
<body>
<div id="box" onmouseover="stop()" onmouseout="start()">
    <div id="red" class="slide"></div>
    <div id="green" class="slide"></div>
    <div id="blue" class="slide"></div>
</div>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读