jQuey網站公告水平滾動程式碼

admin發表於2017-10-31

公告水平滾動程式碼在大量網站都有應用,下面分享一段這樣的程式碼例項。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>螞蟻部落</title>
<style type="text/css">
#container{
  background:#CCCCCC;
  position:relative;
  overflow:hidden;  
  width:550px;
  height:25px;
  line-height:25px;
  margin:100px;
}
#content{
  position:absolute;
  left:0;
  top:0;
  white-space:nowrap;
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
(function($){  
  $.fn.extend({        
    roll:function(options){ 
      var defaults={speed:1};
      var options=$.extend(defaults, options); 
      var speed=(document.all)?options.speed:Math.max(1,options.speed-1);
      if($(this)==null) return ; 
      var $container=$(this);
      var $content=$("#content");
      var init_left=$container.width();
      $content.css({left:parseInt(init_left)+"px"});
      var This=this;
      var time=setInterval(function(){This.move($container,$content,speed);},20);
      $container.bind("mouseover",function(){clearInterval(time);});
      $container.bind("mouseout",function(){
        time=setInterval(function(){This.move($container,$content,speed);},20);
      });
      return this;    
    },
    move:function($container,$content,speed){
      var container_width = $container.width();
      var content_width = $content.width();
      if(parseInt($content.css("left")) + content_width > 0){
        $content.css({left:parseInt($content.css("left")) - speed + "px"});
      }
      else{
        $content.css({left:parseInt(container_width) + "px"});
      }
    }
  });
})(jQuery);
$(document).ready(function(){
  $("#container").roll({speed:2});
});
</script>
</head>
<body>
<div id="container">
  <div id="content">螞蟻部落歡迎您,只有努力奮鬥才會有美好的前途</div>
</div>
</body>
</html>

相關文章