jQuery实现横向滚动切换选中
Posted easonw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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实现横向滚动切换选中的主要内容,如果未能解决你的问题,请参考以下文章