jQuery实现横向滚动切换选中

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
  #container {
    width: 460px;
    height: 200px;
    margin: 50px auto;
    border: 1px solid #ccc;
    overflow: hidden;
    position: relative;
  }
  #box {
    height: 200px;
    position: absolute;
    left: 0;
    top: 0;
  }
  #head, #add, #cards div{
    float: left;
    margin: 0 10px;
    width: 100px;
    height: 100px;
    text-align: center;
    border: 1px solid #ccc;
    box-sizing: border-box;
  }
  #cards {
    float: left;
  }
  #cards div.active {
    width: 200px;
    height: 200px;
  }
</style>
</head>
<body>
  <div id="container">
    <div id="box">
      <div id="head">head</div>
      <div id="cards"></div>
      <div  id="add">tail</div>
    </div>
  </div>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  var arr = [], len = 0, w = 0, index = null;
  
  $(‘#add‘).click(function(e) {
    console.log(e)
    var div = ‘<div class="card active" data-id=‘+ arr.length +‘>‘+ arr.length +‘<button class="del">删除</button></div>‘
    arr.push(div)
    // var str = ‘‘
    // for (let i = 0; i < arr.length; i++) {
    //   str += arr[i]
    // }
    $(‘#cards div‘).removeClass(‘active‘)
    // $(div).addClass(‘active‘)
    $(div).appendTo($(‘#cards‘))

    index = arr.length - 1

    w = 120 * (2 + arr.length) + 220
    $(‘#box‘).css(‘width‘, w)
    if (arr.length > 1) $(‘#box‘).css(‘left‘, -120 * (arr.length -1) + ‘px‘)
  })

  $(‘#box‘).click(function(e) {
    if ($(e.target).hasClass(‘card‘)) {
      console.log($(e.target).attr(‘data-id‘))
      index = $(e.target).attr(‘data-id‘)
      $(‘#box div‘).removeClass(‘active‘)
      $(e.target).addClass(‘active‘)

      if (index >= 0) $(‘#box‘).css(‘left‘, -120 * index + ‘px‘)
    } else if($(e.target).hasClass(‘del‘)) {
      console.log(‘del‘, index, arr)
      arr.splice(index, 1)
      console.log(arr)
      $(e.target).parent().remove()
    }
  })
</script>
</body>
</html>

  

jQuery实现横向滚动切换选中

上一篇:kubernetes云平台管理实战:k8s弹性伸缩(十八)


下一篇:Python+Appium学习篇之WebView处理