用JQuery实现一个轮播

HTML

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div class="window">
  <div class="images" id="images">
    <img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg" width=300 alt="图片1" height=200>
      <img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg" width=300 alt="" height=200>
      <img src="https://fthmb.tqn.com/0ui_Zw01Ht9NHJkSBlqOIC1IH44=/960x0/filters:no_upscale()/yorkshire-terrier-583788122-581630e85f9b581c0b018a00.jpg" width=300 alt="" height=200>
      <img src="https://canna-pet.com/wp-content/uploads/2017/06/20-longest-living-dog-breeds_canna-pet-e1498599846169.jpg" width=300 alt="" height=200>
  </div>
</div>
  <div id="buttons">
    <button>第1张</button>
    <button>第2张</button>
    <button>第3张</button>
    <button>第4张</button>
  </div>
</body>
</html>

JS

var allButtons = $('button')

for(let i=0; i<allButtons.length; i++){
  //JQ遍历点击事件
  $(allButtons[i]).on('click', function(x){
    //currentTarget:选择当前点击对象。index():在兄弟中排第几位
    var index = $(x.currentTarget).index()
    var p = index * -300
    //transform:位移。translate:移动距离
    $('#images').css({
      transform: 'translate('+ p + 'px)'
    })
    n =index
    //eq:JQuery将DOM对象封装成JQ对象,可直接进行JQ操作,不用二次封装。siblings:兄弟元素
    //allButtons.eq(n).addClass('red').siblings('.red').removeClass('red')
    activeButton(allButtons.eq(n))
  })
}

var n = 0;
var size = allButtons.length
//trigger:后面可以接任何事件名,比click功能强大。
allButtons.eq(n % size).trigger('click')

var timerId = setTimer()

function setTimer() {
  return setInterval(()=>{
  n +=1
  allButtons.eq(n % size).trigger('click')
  },1500)
}

function activeButton($button) {
  $button.addClass('red').siblings('.red').removeClass('red')
}

//mouseenter:鼠标进入被选元素
$('.window').on('mouseenter', function(){
  window.clearInterval(timerId)
})
//mouseleave:鼠标离开被选元素
$('.window').on('mouseleave', function(){
  timerId = setTimer()
})

CSS

.window{
  width: 300px;
  overflow: hidden;
}
.images{
  display: flex;
  transition: all .5s;
}
.red{
  color: red;
}
#buttons{
  margin-top: 10px;
}
button{
  cursor: pointer;
}

demo地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值