JS 实现banner图的滚动和选择效果

Posted 戴瓜皮帽的奸商猴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS 实现banner图的滚动和选择效果相关的知识,希望对你有一定的参考价值。

CSS+JS实现banner图滚动和点击切换

html 部分代码:

<body>

<div id="banner">
  <div id="inside"><img src="img/banner1.png" id="img1" /><img src="img/banner2.png" id="img2" /><img src="img/banner3.png" id="img3" /><img src="img/banner4.png" id="img4" /><img src="img/banner1.png" id="img5" />
</div>

<ul id="bannerNum">
  <li onclick="changeBanner(1)">1</li>
  <li onclick="changeBanner(2)">2</li>
  <li onclick="changeBanner(3)">3</li>
  <li onclick="changeBanner(4)">4</li>
</ul>
</div>

</body>

CSS代码:

<style type="text/css">
*{
padding: 0px;
margin: 0px;
}

#banner{
width: 100%;
overflow: hidden;
white-space: nowrap;
position: relative;
}

#banner #inside{
width: 9600px;
position: relative;
left: 50%;
margin-left: -960px;
transition: all 1s ease;
}

#banner img{
width: 1920px;
}

#bannerNum{
padding: 0px;
list-style: none;
overflow: hidden;
width: 160px;
position: absolute;
bottom: 30px;
right: 50px;
}

#bannerNum li{
width: 30px;
height: 30px;
background-color: white;
text-align: center;
line-height: 30px;
margin: 0px 5px;
float: left;
cursor: pointer;
}

</style>

JS 部分代码:

<script>
  var num = 1;
  var inside;
  window.onload = function(){

  inside = document.getElementById("inside");

  var interval = setInterval(function(){
    inside.style.transition = "all 1s ease";
    num++;
    switch (num){
    case 1:
    inside.style.transition = "none";
    inside.style.marginLeft = (-960)+"px";
    break;
    case 2:
    inside.style.marginLeft = (-960-1920)+"px";
    break;
    case 3:
    inside.style.marginLeft = (-960-1920*2)+"px";
    break;
    case 4:
    inside.style.marginLeft = (-960-1920*3)+"px";
    break;
    case 5:
    inside.style.marginLeft = (-960-1920*4)+"px";
    num = 0;
    break;
    default:
    break;
    }
    },2000);
  }

  function changeBanner(num1){
    inside.style.transition = "none";
    switch (num1){
    case 1:
    inside.style.marginLeft = (-960)+"px";
    break;
    case 2:
    inside.style.marginLeft = (-960-1920)+"px";
    break;
    case 3:
    inside.style.marginLeft = (-960-1920*2)+"px";
    break;
    case 4:
    inside.style.marginLeft = (-960-1920*3)+"px";
    break;
    default:
    break;
    }

  num = num1-1;

  }
</script>

 

以上是关于JS 实现banner图的滚动和选择效果的主要内容,如果未能解决你的问题,请参考以下文章

原生JS实现banner图的滚动与跳转

如何使用JS实现banner图滚动

原生JS和jQuery实现banner图滚动那些事

使用原生javascript实现网页中banner滚动切换效果

这个Top Banner滚动效果是如何实现的?

原生JS实现各种经典网页特效——Banner图滚动选项卡切换广告弹窗等