close
文章出處
無縫連續滾動JS,工作中經常會用到整理出來需要用的時候可以直接拿來用。代碼很簡單主要就是修改元素的scrollLeft值。需要注意的是獲取元素overflow:hidden中內容的真實寬高時,需要先克隆元素并內容設置樣式setyle.cssText="position;absolute; visibility:visible;display:block;" 。 然后再使用元素的offsetWidth/offsetWidth屬性才可以獲取到元素的真實寬高。否則被隱藏部分的寬高無法獲取到。
代碼:
<!DOCTYPE html > <html> <head> <meta charset="utf-8" /> <title>通用無縫連續滾動JS(by rentj1@163.com;)</title> <style> body{ font-size:12px;} #scroll{width:500px; overflow:hidden } .referer{ margin-top:50px;} </style> </head> <body> <div id="scroll"> <a href="#" target="_blank">關注反彈成交量</a> <font color="#999999">11:22</font> <a href="#" target="_blank">中信建投期貨:關注甲醇60日均線的得失</a> <font color="#999999">11:21</font> <a href="#" target="_blank">大盤技術性反抽 不宜過分樂觀</a> <font color="#999999">11:21</font> <a href="#" target="_blank">中證期貨:PVC市場恐難改低迷</a> <font color="#999999">11:21</font> </div> <script> (function(ns){ //Class Scroll{ /** * 構造函數 * email: rentj1@163.com; * @param {HTMLElement} 滾動內容的容器 * @return {Undefined} */ function Scroll(element){ var content = document.createElement("div"); var container = document.createElement("div"); var _this =this; var cssText = "position: absolute; visibility:hidden; left:0; white-space:nowrap;"; this.element = element; this.contentWidth = 0; this.stop = false; content.innerHTML = element.innerHTML; //獲取元素真實寬度 content.style.cssText = cssText; element.appendChild(content); this.contentWidth = (getComputedStyle && parseFloat(getComputedStyle(content,null).width)) || content.offsetWidth; content.style.cssText= "float:left;"; container.style.cssText = "width: " + ((this.contentWidth) * 2) + "px; overflow:hidden"; container.appendChild(content); container.appendChild(content.cloneNode(true)); element.innerHTML = ""; element.appendChild(container); container.onmouseover = function(e){ clearInterval(_this.timer); }; container.onmouseout = function(e){ _this.timer = setInterval(function(){ _this.run(); },20); }; _this.timer = setInterval(function(){ _this.run(); }, 20); } Scroll.prototype = { run: function(){ var _this = this; var element = _this.element; element.scrollLeft = element.scrollLeft + 2; if(element.scrollLeft >= this.contentWidth ) { element.scrollLeft = 0; } } }; //} ns.Scroll = Scroll; //參考:<br /> //http://www.ilovejs.net/archives/108 }(window)); var elem = document.getElementById("scroll"); var sc = new Scroll(elem); </script> </body> </html>
更新:2012930
代碼說明:
this.contentWidth = (getComputedStyle && parseFloat(getComputedStyle(content,null).width)) || content.offsetWidth;
1 在IE9使用 content.offsetWidth獲取元素的寬度時,得到值會忽略小數位數,使用 getComputedStyle 可以獲取元素的實際寬度。
2 在IE/6/7/8中使用元素的currentStyle屬性兼容getComputedStyle 時,如果沒有顯式指定元素的width,height樣式值會返回auto。
![]() |
不含病毒。www.avast.com |
全站熱搜