实现轮播的一般思路为在一个大盒子中对无限个元素进行切换操作,大盒子固定大小,超出盒子范围进行隐藏,而里面无限个元素可以任何堆叠,按照一定的步骤进行位置变换,已达到在可视区域呈现我们想要的效果。
看一个实例:
HTML代码:
1 <div class="trans_box"> 2 <div id="transImageBox" class="trans_image_box"> 3 <div class="trans_image" style="width:300px;height:200px;background:blue;">111</div> 4 <div class="trans_image" style="width:300px;height:200px;background:red;">222</div> 5 <div class="trans_image" style="width:300px;height:200px;background:orange;">333</div> 6 </div> 7 <div id="transImageTrigger" class="trans_image_trigger"> 8 <a href="#1">图片1</a> <a href="#2">图片2</a> <a href="#3">图片3</a> 9 </div> 10 </div>
CSS代码:
1 .trans_box { 2 width:300px; 3 overflow:hidden; 4 } 5 .trans_image_box { 6 width:20000px; 7 height:200px; 8 -webkit-transition: all 1s ease-in-out; 9 -moz-transition: all 1s ease-in-out; 10 -o-transition: all 1s ease-in-out; 11 transition: all 1s ease-in-out; 12 } 13 .trans_image_box .trans_image { 14 float:left; 15 width:200px; 16 } 17 .trans_image_trigger { 18 padding-top: 10px; 19 text-align: center; 20 }
JS代码:
1 var $ = function(id) { 2 return document.getElementById(id); 3 }; 4 var $box = $("transImageBox"), 5 $oTrigger = $("transImageTrigger").getElementsByTagName("a"), 6 $len = $oTrigger.length; 7 for(var i = 0; i < $len; i++) { 8 $oTrigger[i].onclick = function(){ 9 var index = Number(this.href.replace(/.*#/g,‘‘)) || 1; 10 $box.style.marginLeft = (1 - index) * 300 + "px"; 11 return false; 12 }; 13 }
时间: 2024-12-11 15:52:12