在開發網站時,首頁不免會遇到須要滾動展現圖片的時候,從其餘網站搜刮了點代碼,分享於此:
javascript
<html lang="zh-CN"><head> <meta charset="utf-8"> <title>jQuery無縫滾動</title> <style> .scroll-container { width: 800px; margin: 50px auto; } .scroll { width: 800px; border: 1px solid #ccc; overflow: hidden; } .scroll ul { white-space: nowrap; } .scroll ul li { display: inline-block; margin: 10px; } .scroll ul img { vertical-align: top; } </style> </head> <body style=""> <div class="scroll-container"> <div class="scroll"> <ul style="margin-left: -43px;"> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0003.png" alt=""></li> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0004.png" alt=""></li> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0005.png" alt=""></li> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0006.png" alt=""></li> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0001.png" alt=""></li> <li><img src="http://www.jq22.com/demo/jqueryscroll201903112313/images/0002.png" alt=""></li> </ul> </div> </div> <script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> <script> (function($){$.fn.scroll=function(options){var defaults={speed:30,direction:'vertical'};var opts=$.extend({},defaults,options),intId=[];function marquee(obj,step,direction){if(direction=='horizantal'){obj.find("ul").animate({marginLeft:'-=1'},0,function(){var s=Math.abs(parseInt($(this).css("margin-left")));if(s>=step){$(this).find("li").slice(0,1).appendTo($(this));$(this).css("margin-left",0);}});}else if(direction=='vertical'){obj.find("ul").animate({marginTop:'-=1'},0,function(){var s=Math.abs(parseInt($(this).css("margin-top")));if(s>=step){$(this).find("li").slice(0,1).appendTo($(this));$(this).css("margin-top",0);}});}} this.each(function(i){var speed=0<100-opts["speed"]&&100-opts["speed"]<=100?100-opts["speed"]:30;var direction=opts["direction"]=='vertical'||opts["direction"]=='horizantal'?opts["direction"]:'vertical';var _this=$(this);intId[i]=setInterval(function(){var sh;if(direction=='horizantal'){sh=_this.find("ul").find("li:first").outerWidth(true);}else{sh=_this.find("ul").find("li:first").outerHeight(true);} marquee(_this,sh,direction);},speed);_this.hover(function(){clearInterval(intId[i]);},function(){intId[i]=setInterval(function(){var sh;if(direction=='horizantal'){sh=_this.find("ul").find("li:first").outerWidth(true);}else{sh=_this.find("ul").find("li:first").outerHeight(true);} marquee(_this,sh,direction);},speed);});});}})(jQuery); </script> <script type="text/javascript"> $(function () { $('.scroll').scroll({ speed: 80, //數值越大,速度越快 direction: 'horizantal' }); }); </script> </body></html>