主要原理:利用絕對定位+overflow+CSS3動畫javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>圖片輪播</title> <style> .bg{ width: 20.5em; min-height: 10em; margin: 0 auto; position: relative; overflow: hidden; background-color: white; } #picBox{ position: absolute; min-height: 10em; min-width: 150em; left: -40em; } .picBoxR{ animation: spinR 1s linear; } .picBoxL{ animation: spinL 1s linear; } #picBox div{ margin-right: 2px; float: left; text-align: center; background-color: darkblue; color: white; /*margin-right: 0.2em;*/ width: 20em; height: 10em; line-height: 10em; } .act{ position: absolute; top: 3.5em; background: rgba(0,0,0,0); } .act a{ color: yellow; outline: none; text-decoration: none; font-size: 2em; margin-left: 4px; } .act a:active{ color: white; background: rgba(0,0,0,0.3); } .act a:hover{ color: white; background: rgba(0,0,0,0.3); } .act:last-child{ left: 18em; } @keyframes spinR{ 0% { transform:translateX(0em); }100%{ transform:translateX(-20em); } } @keyframes spinL{ 0% { transform:translateX(0em); }100%{ transform:translateX(20em); } } </style> </head> <body> <div class="bg"> <div id="picBox"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> </div> <!--兩個方向箭頭--> <div class="act"><a href="javascript:;" >⇦</a></div> <div class="act"><a href="javascript:;" >⇨</a></div> </div> <script src="../js/jquery-3.2.1.js"></script> <script> $('.act').click(function () { var curL = $('#picBox').css('left'); var animator = document.getElementById('picBox'); console.log('\n curL = ' + curL); var curlN = ''; if($(this).text() == '\u21E8' ){ // 點擊向右 // 動態添加動畫 //等待動畫完成以後進行位移變換 animator.className = ''; setTimeout(function () { animator.className = 'picBoxR'; }, 0); setTimeout(function () { curlN = parseInt(curL)/16 - 20 + 'em'; $('#picBox').css('left',curlN); var curL2 = $('#picBox').css('left'); console.log('\n curL2 = ' + curL2); var $one_li = $("#picBox div:first-child"); var $four_li = $("#picBox div:last-child"); $one_li.insertAfter($four_li); $('#picBox').css('left','-40em'); }, 1000); }else if($(this).text() == '\u21E6'){ //點擊向左 //動態添加動畫 animator.className = ''; setTimeout(function () { animator.className = 'picBoxL'; }, 0); //等待動畫完成以後進行位移變換 setTimeout(function () { //進行位移計算 並 位移 curlN = parseInt(curL)/16 + 20 + 'em'; $('#picBox').css('left',curlN); //位移完成以後當即進行先後調換 var last = $("#picBox div:last-child"); var first = $("#picBox div:first-child"); last.insertBefore(first); //回到起始位置 $('#picBox').css('left','-40em'); }, 1000); }else return false; }); </script> </body> </html>