国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js模擬滾動條(橫向豎向)

2019-11-20 22:59:15
字體:
供稿:網(wǎng)友

JS:

復制代碼 代碼如下:

(function(win){
    var doc = win.document,db = doc.body;
    var mousewheel = 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
    var skyScroll = function(opts){ return new skyScroll.prototype.init(opts);};
    skyScroll.prototype = {
        constructor:skyScroll,
        //初始化
        init:function(opts){
            var set = _extend({
                target:'contentbox',
                dir:'top',
                width:500,
                height:300,
                callback:function(){}
            },opts||{});
            var _this = this,mousemoveHandle,mousedownHandle;
            this.target = _$(set.target);
            this.parent = this.target.parentNode;
            this.width = set.width;
            this.height = set.height;
            this.dir = set.dir;
            this.callback = set.callback;
            this.addWarpper(set.dir);
            switch(set.dir){
                case 'top':
                    this.addVscroll();
                    break;
                case 'left':
                    this.addLscroll();
                    break;
                default :
                    this.addVscroll();
                    this.addLscroll();
            };
            _addEvent(doc,'mousedown',function(e){
                var e = e || window.event,target = e.target || e.srcElement,pos= _getMousePos(e);
                if(target == _this.vScroll || target == _this.lScroll){
                    pos.tTop = parseInt(_this.target.style.top);
                    pos.tLeft = parseInt(_this.target.style.left);
                    pos.sTop = parseInt(target.style.top);
                    pos.sLeft = parseInt(target.style.left);
                    mousemoveHandle = _mousemoveHandle.call(_this,pos,target);
                    _addEvent(doc,'mousemove',mousemoveHandle);
                    _addEvent(doc,'mouseup',function(){_removeEvent(doc,'mousemove',mousemoveHandle)});
                };
                if(target == _this.vScrollOuter || target == _this.lScrollOuter){
                    _mounsedownHandle.call(_this,pos,target);
                };
            });
        },  
        //對外提供重新計算滾動條高度或?qū)挾纫约皾L動范圍的方法,用于動態(tài)改變內(nèi)容時,作出的相對應的調(diào)整
        recalculated:function(){
            var H = this.target.offsetHeight,W = this.target.offsetWidth,T = parseInt(this.target.style.top),L = parseInt(this.target.style.left),h,w;
            this.ratio = {l:this.width / W,v:this.height / H};
            this.range = {l:W-this.width, t: H - this.height};
            if(this.vScroll){
                h = Math.round(Math.pow(this.height,2) / H);
                this.vScroll.style.height = h+'px';
                this.vScroll.style.top = Math.round(this.height * (-T/H)) + 'px';
                this.range.st = this.height - h;
                this.wrapper.style.height = this.height + 'px';
            };
            if(this.lScroll){
                w = Math.round(Math.pow(this.width,2) / W)
                this.lScroll.style.width = w + 'px';
                this.lScroll.style.left = Math.round(this.width * (-L/W)) + 'px';
                this.range.sl = this.width - w;
                this.wrapper.style.width = this.width + 'px';
            };
        },
        //對外提供設置滾動條的位置的方法
        set:function(pos){
            if(!_isObject(pos)) throw new Error('參數(shù)類型錯誤,參數(shù)必須是object!');
            if(pos.top && !isNaN(parseInt(pos.top)) && this.vScroll){
                var top = Math.min(pos.top,this.range.t);
                this.target.style.top = -top + 'px';
                this.vScroll.style.top = Math.round(this.height * (top / this.target.offsetHeight)) + 'px';
            };
            if(pos.left && !isNaN(parseInt(pos.left)) && this.lScroll){
                var left = Math.min(pos.left,this.range.l);
                this.target.style.left = -left + 'px';
                this.lScroll.style.left = Math.round(this.width * (left / this.target.offsetWidth)) + 'px';
            };
        },
        addWarpper:function(dir){
            if(this.wrapper) return;
            var _this = this,W = this.target.offsetWidth,H = this.target.offsetHeight,mousewheelHandle;
            this.wrapper = _createEl('<div class="sky_warpper" style="position:relative;overflow:hidden;"></div>',this.parent);
            this.wrapper.appendChild(this.target);
            this.target.style.cssText = 'position:absolute;top:0;left:0';
            switch(dir){
                case 'top':
                    this.wrapper.style.height = this.height + 'px';
                    this.wrapper.style.width = W + 'px';
                    break;
                case 'left':
                    this.wrapper.style.height = H + 'px';
                    this.wrapper.style.width = this.width + 'px';
                    break;
                default :
                    this.wrapper.style.width = this.width + 'px';
                    this.wrapper.style.height = this.height + 'px';
            };
            _addEvent(this.wrapper,'mouseenter',function(e){
                var pos = {};
                pos.tTop = parseInt(_this.target.style.top);
                pos.tLeft = parseInt(_this.target.style.left);
                if(_this.vScroll) pos.sTop = parseInt(_this.vScroll.style.top);
                if(_this.lScroll) pos.sLeft = parseInt(_this.lScroll.style.left);
                mousewheelHandle = _mousewheelHandle.call(_this,pos);
                _addEvent(_this.wrapper,'mousewheel',mousewheelHandle);
                _addEvent(_this.wrapper,'mouseleave',function(){_removeEvent(_this.wrapper,'mousewheel',mousewheelHandle)});
            });
        },
        //對外提供添加豎向滾動條的方法
        addVscroll:function(){
            if(this.vScroll) return;
            !this.wrapper && this.addWarpper('top');
            this.vScrollOuter = _createEl('<div class="sky_scrollTopOuter" style="position:absolute;top:0;right:0;height:'+this.height+'px;overflow:hidden"></div>',this.wrapper)
            this.vScroll = _createEl('<div class="sky_scrollTop" style="position:absolute;top:0;right:0;"></div>',this.wrapper);
            this.recalculated();
        },
        //對外提供添加橫向滾動條的方法
        addLscroll:function(){
            if(this.lScroll) return;
            !this.wrapper && this.addWarpper('left');
            this.lScrollOuter = _createEl('<div class="sky_scrollLeftOuter" style="position:absolute;bottom:0;left:0;width:'+this.width+'px;overflow:hidden"></div>',this.wrapper)
            this.lScroll = _createEl('<div class="sky_scrollLeft" style="position:absolute;left:0;bottom:0;"></div>',this.wrapper);
            this.recalculated();
        },
        //刪除豎向滾動條
        delVscroll:function(){
            _deleteScroll.call(this,1,this.vScroll,this.vScrollOuter,this.lScroll,this.lScrollOuter);
        },
        //刪除橫向滾動條   
        delLscroll:function(){
            _deleteScroll.call(this,0,this.lScroll,this.lScrollOuter,this.vScroll,this.vScrollOuter);
        }
    };
    skyScroll.prototype.init.prototype = skyScroll.prototype;
    window.skyScroll = skyScroll;
    /*************************私有函數(shù)*************************/
    function _mousemoveHandle(pos,target){
        var _this = this;
        return target == this.vScroll ? function(e){
            e = e || window.event;
            var newPos = _getMousePos(e);
            _this.target.style.top = Math.min(0,Math.max(pos.tTop + (pos.y - newPos.y)/_this.ratio.v,-_this.range.t)) + 'px';
            target.style.top = Math.max(0,Math.min(pos.sTop - pos.y + newPos.y,_this.range.st))+ 'px';
            _this.callback.call(_this);
            _cancelSelect()
        }:function(e){
            e = e || window.event;
            var newPos = _getMousePos(e);
            _this.target.style.left = Math.min(0,Math.max(pos.tLeft + (pos.x - newPos.x)/_this.ratio.l,-_this.range.l)) + 'px';
            target.style.left = Math.max(0,Math.min(pos.sLeft - pos.x + newPos.x,_this.range.sl)) + 'px';
            _this.callback.call(_this);
            _cancelSelect();
        }
    };

    function _mousewheelHandle(pos){
        var _this = this;
        return this.vScroll ? function(e){
            e = e || window.event;
            _stopEvent(e);
            var data = e.wheelDelta ? e.wheelDelta /120 : -e.detail/3;
            var top = parseInt(_this.target.style.top);
            var sTop = parseInt(_this.vScroll.style.top);
            var dist = data * 5;
            _this.target.style.top = Math.min(0,Math.max(top + dist / _this.ratio.v, -_this.range.t)) + 'px';
            _this.vScroll.style.top = Math.max(0,Math.min(sTop-dist,_this.range.st)) + 'px';
            _this.callback.call(_this);
        }:function(e){
            e = e || window.event;
            _stopEvent(e);
            var data = e.wheelDelta ? e.wheelDelta /120 : -e.detail/3;
            var left = parseInt(_this.target.style.left);
            var sLeft = parseInt(_this.lScroll.style.left);
            var dist = data * 5;
            _this.target.style.left = Math.min(0,Math.max(left + dist / _this.ratio.l, -_this.range.l)) + 'px';
            _this.lScroll.style.left = Math.max(0,Math.min(sLeft-dist,_this.range.sl)) + 'px';
            _this.callback.call(_this);
        }
    };
    function _mounsedownHandle(pos,target){
        var _this = this;
        var elPos = _getElementPosition(target);
        if(target == this.vScrollOuter){
            console.log(pos.y - elPos.y);
            _this.set({
                top:pos.y - elPos.y
            });
        }else{
            _this.set({
                left:pos.x - elPos.x
            });
        };
    };
    function _deleteScroll(n,s1,s11,s2,s22){
        var o = n ? 'Height' : 'Width' ,s = n ? 'top' : 'left';
        if(!s1) return;
        this.wrapper.removeChild(s1);
        this.wrapper.removeChild(s11);
        n ?  (this.vScroll = null) : (this.lScroll = null);
        if(!s2){
            this.wrapper.parentNode.appendChild(this.target);
            this.wrapper.parentNode.removeChild(this.wrapper);
            this.target.style.cssText = '';
            this.wrapper = null;
        }else{
            this.wrapper.style[o.toLowerCase()] = this.target['offset'+o] + 'px';
            this.recalculated();
        };
        this.target.style[s] = '0px';
        //this.target.style[o.toLowerCase()]= 'auto';
    };
    /*************************工具函數(shù)*************************/
    function _$(id){
        return typeof id === 'string' ? doc.getElementById(id) : id;
    };
    function _extend(target,source){
        for(var key in source) target[key] = source[key];
        return target;
    };
    function _createEl(html,parent){
        var div = doc.createElement('div');
        div.innerHTML = html;
        el = div.firstChild;
        parent && parent.appendChild(el);
        return el;
    };
    function _getMousePos(e){
        if(e.pageX || e.pageY) return {x:e.pageX,y:e.pageY};
        return {
            x:e.clientX + document.documentElement.scrollLeft - document.body.clientLeft,
            y:e.clientY + document.documentElement.scrollTop - document.body.clientTop
        };
    };
    function _isObject(o){
        return o === Object(o);
    };
    function _getElByClass(node,oClass,parent){
        var re = [],els,parent = parent || doc;
        els = parent.getElementsByTagName(node);
        for(var i=0,len=els.length;i<len;i++){
            if((' ' + els[i].className+' ').indexOf(' '+oClass+' ') > -1) re.push(els[i]);
        };
        return re;
    };
    function _stopEvent(e){
        e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
        e.preventDefault ? e.preventDefault() :(e.returnValue = false);
    };
    function _addEvent(el,type,fn){
        if(typeof el.addEventListener != 'undefined'){
            if(type == 'mouseenter'){
                el.addEventListener('mouseover',_findElement(fn),false);
            }else if(type === 'mouseleave'){
                el.addEventListener('mouseout',_findElement(fn),false);
            }else{
                el.addEventListener(type,fn,false);
            }
        }else if(typeof el.attachEvent != 'undefined'){
            el.attachEvent('on'+type,fn);
        }else{
            el['on'+type] = fn;
        }
    };
    function _removeEvent(el,type,fn){
        if(typeof el.removeEventListener != 'undefined'){
            el.removeEventListener(type,fn,false);
        }else if(typeof el.detachEvent != 'undefined'){
            el.detachEvent('on'+type,fn);
        }else{
            el['on'+type] = null;
        }
    };
    function _findElement(fn){
        return function(e){
            var parent = e.relatedTarget;
            while(parent && parent != this) parent = parent.parentNode;
            if(parent != this) fn.call(this,e);
        }
    };
    function _cancelSelect(){
        if (window.getSelection) {
            if (window.getSelection().empty) {  // Chrome
                window.getSelection().empty();
            } else if (window.getSelection().removeAllRanges) {  // Firefox
                window.getSelection().removeAllRanges();
            }
        }else if (document.selection) {  // IE?
          document.selection.empty();
        }
    };
    function _getElementPosition(el){
        var x = 0,y=0;
        if(el.getBoundingClientRect){
            var pos = el.getBoundingClientRect();
            var d_root = document.documentElement,db = document.body;
            x = pos.left + Math.max(d_root.scrollLeft,db.scrollLeft) - d_root.clientLeft;
            y = pos.top + Math.max(d_root.scrollTop,db.scrollTop) - d_root.clientTop;
        }else{
            while(el != db){
                x += el.offsetLeft;
                y += el.offsetTop;
                el = el.offsetParent;
            };
        };
        return {
            x:x,
            y:y
        };
    };
})(window);

HTML:

復制代碼 代碼如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title></title>
    <style type="text/css">
        * { margin:0; padding:0;}
        body {font-size:12px; line-height:1.5;}
        #scrollTest {background:#fff;padding:10px;width:1000px;}
        .sky_warpper { margin:100px auto;background:red;}
        .sky_scrollTopOuter {width:7px;background:#ddd;opacity:0.3;}
        .sky_scrollTopOuter:hover {opacity:0.8;width:7px;-webkit-transition:opacity,width 0.3s ease-out;}
        .sky_scrollTop { background:#333;opacity:0.3;width:7px;-webkit-border-radius:5px;-webkit-transition:opacity,width 0.3s ease-out; cursor:default;}
        .sky_warpper:hover .sky_scrollTop { opacity:0.8;width:7px;-webkit-transition:opacity,width 0.3s ease-out;}

        .sky_scrollLeftOuter {height:7px;background:#ddd;opacity:0.3;}
        .sky_scrollLeftOuter:hover {opacity:0.8;height:7px;-webkit-transition:opacity,height 0.3s ease-out;}
        .sky_scrollLeft { background:#333;opacity:0.3;height:7px;-webkit-border-radius:5px;-webkit-transition:opacity,height 0.3s ease-out; cursor:default;}
        .sky_warpper:hover .sky_scrollLeft { opacity:0.8;height:7px;-webkit-transition:opacity,height 0.3s ease-out;}
    </style>
</head>
<body>
    <input type="button" id="addSt" value="添加豎向滾動條" />
    <input type="button" id="addSl" value="添加橫向滾動條" />
    <input type="button" id="delSt" value="刪除豎向滾動條" />
    <input type="button" id="delSl" value="刪除橫向滾動條" />
    <input type="button" id="add" value="增加內(nèi)容" />
    <input type="button" id="setTop" value="設置上邊距離" />
    <input type="button" id="setLeft" value="設置左邊距離" />
    <div id="scrollTest">
        111111111111111111111111111111譯者按 IE 曾是 web 創(chuàng)新的先驅(qū),但最近幾年因為對 web 標準的支持落后于其他瀏覽器以及低版本 IE 的各種 bug 而被人詬病。雅虎的 Nicholas C. Zakas 帶我們回顧了 IE 在 web 發(fā)展過程中扮演的輝煌角色,讓我們能以一個更客觀的眼光來看待 IE。看完這篇文章,也許大家都會對 IE 瀏覽器有一定的改觀,這也是我翻譯這篇文章的目的。

譯文

在 Internet Explorer 成為大家都恨之入骨的瀏覽器的很久以前,它曾是整個互聯(lián)網(wǎng)的創(chuàng)新驅(qū)動力。有時候我們很難記得那些在 IE 6 成為全世界 web 開發(fā)者的災難之前 IE 所作的貢獻。不管你信不信,正因為有了 IE 4―6,才會有我們現(xiàn)在所知的 web 開發(fā)。IE 的一些獨特的功能過去就曾是事實標準,后來成為了官方標準最終進入了 HTML5 規(guī)范。人們也許很難相信,對于我們現(xiàn)在認為理所應當?shù)墓δ苤杏泻艽笠徊糠侄紤撘氲?IE,但快速地回顧一下歷史可以讓我們知道的確如此。

DOM

如 果 IE 是一個人人都痛恨的瀏覽器,那么「文檔對象模型」(DOM)就是人人都痛恨的 API 了。你可以說 DOM 過于繁瑣、不適合 JavaScript 甚至是有些荒謬,而且這些也都沒錯。然而,DOM 還是給了開發(fā)者通過 JavaScript 來訪問網(wǎng)頁的每個部分的途徑。曾經(jīng)你一度只能通過 JavaScript 訪問頁面中某些特定的元素。IE 3 和 Netscape 3 只允許程序訪問表單元素、圖片以及鏈接。Netscape 4 改進了這一點,把程序可訪問的范圍通過 document.layers 擴展到了它特有的 layer 元素。IE 4 作了進一步改進,把這個范圍通過 document.all 擴展到了頁面的所有元素。

從很多方面來說,document.all 算是 document.getElementById() 的最初版本。你還是要使用元素的 ID 來通過 document.all 訪問它,例如 document.all.myDiv 或是 document.all["myDiv"]。最主要的區(qū)別就是 IE 使用了一個集合而非方法,而這和其他當時的訪問方法比如 document.images 及 document.forms 是相吻合的。

IE 4 也第一個引入了用 document.all.tags() 來通過標簽名字獲取一個元素列表的功能。無論從哪點來看,這都是 document.getElementsByTagName() 的最初版本,而且工作方式完全相同。如果你想獲取所有的 div 元素,你可以使用 document.all.tags("div")。甚至在 IE 9 中,這個方法仍然作為 document.getElementsByTagName() 的一個別名存在。

IE 4 同時也為我們引入了可能是有史以來最流行的私有 DOM 擴展:innerHTML。看起來微軟的那幫人是認識到了通過編程手段來建立一個 DOM 有多么痛苦,所以把這個便捷方法,連同 outerHTML 一起提供給我們。事實證明這兩個方法都非常有用,已經(jīng)在 HTML5 中被標準化了[1]。隨它們一同而來的用來處理純文本的 API――innerText 以及 outerText――同樣被證明足夠有影響力,因為 DOM Level 3 已經(jīng)引入了與 innerText 行為相似的 textContent[2]。

按照同樣的思路,IE 4 引入了 insertAdjacentHTML(),這是又一種將 HTML 插入文檔中的方法。雖然這花了更長的時間,但最終也被編入了 HTML5[3],而且目前已被各瀏覽器廣泛支持。

事件

在開始時,JavaScript 并沒有事件機制。網(wǎng)景和微軟都作出了嘗試,并且分別得出了不同的模型。網(wǎng)景給我們帶來了事件捕獲,其思想是一個事件先發(fā)送到窗口,然后是文檔,然后一個個直到最終到達預期的目標。網(wǎng)景瀏覽器 6 以前的版本都僅支持事件捕獲。

微 軟采取了一個相反的方法,設計出了事件冒泡。他們認為一個事件應該先從實際的目標出發(fā),然后在上層節(jié)點觸發(fā)直到文檔。IE 9 以前的瀏覽器僅支持事件冒泡。雖然隨著官方的 DOM 事件規(guī)范發(fā)展,同時包含了事件捕獲和事件冒泡,但大多數(shù) web 開發(fā)者都只使用事件冒泡,而把事件捕獲僅僅留在 JavaScript 類庫中的一些解決方案和小技巧中使用。

除了創(chuàng)造了事件冒泡以外,微軟還創(chuàng)造了一系列后來也最終被標準化的額外事件:

contextmenu 主站蜘蛛池模板: 天台县| 沽源县| 灯塔市| 渝中区| 滨海县| 丽江市| 勐海县| 太湖县| 日照市| 青铜峡市| 高州市| 交口县| 望江县| 南漳县| 鲁甸县| 阳春市| 三原县| 岢岚县| 舒兰市| 曲沃县| 贵定县| 本溪| 驻马店市| 江达县| 山东省| 黔江区| 武强县| 长寿区| 辽中县| 共和县| 汝阳县| 新源县| 方城县| 浙江省| 内江市| 清涧县| 建宁县| 文安县| 那曲县| 舒城县| 新绛县|