美文网首页
js封装tab可滑动到中间位置

js封装tab可滑动到中间位置

作者: Raral | 来源:发表于2022-01-13 19:15 被阅读0次
(function (window) {
    function Scroller(options) {
        options = Object.assign({}, Scroller.defaultOptions, options);
        this.options = options;
        this.parentNode = document.getElementsByClassName(options.parentNode)[0];
        this.ulNode = document.getElementsByClassName(options.ulNode)[0];
        this.itemNodes = document.getElementsByClassName(options.itemNodes);
        this.init();
    }
    Scroller.prototype = {
        constructor: Scroller,
        init: function () {
            debugger;
            this.scrollLeft = 0;
            this.parentWidth = this.parentNode.offsetWidth;
            this.ulWidth = 0;
            //修改长度
            for(let i = 0, len = this.itemNodes.length; i < len; i ++) {
                this.ulWidth += this.itemNodes[i].offsetWidth;
            }
            //记录样式
            this.style = `width:${this.ulWidth}px; display: flex;justify-content: flex-start;`
            this.ulNode.style = this.style;
            this.bindEvent(this.ulNode,"click", this.switchHandler);
        },
        switchHandler: function (e) {
            let index = e.target.dataset.index;
            this.ativeClassHandle(index);
            this.removeHandle(index);
        },

        removeHandle: function (index) {
            //获取一个元素长度
            let itemWidth = this.itemNodes[0].offsetWidth;
            //获取index内总长度
            let widthTotal = 0;
            for(i = 0; i <= index; i ++) {
                widthTotal += itemWidth;
            }
            console.log(widthTotal,itemWidth / 2, 1100/2);
            if(widthTotal - itemWidth / 2 > this.parentWidth / 2 ) {
                this.scrollLeft = widthTotal - itemWidth / 2 - this.parentWidth / 2;

            }else {
                this.scrollLeft = 0;
            }
            //边界处理
            if(this.scrollLeft > this.ulWidth - this.parentWidth) {
                return;
            }
            this.ulNode.style = this.style + `transition: all ${this.options.time}s; transform: translateX(-${this.scrollLeft}px);`
        },
        //自定义处理选中样式
        ativeClassHandle: function (index) {

        },
        bindEvent: function(node,event,cb) {
            node.addEventListener(event, function(e) {
                cb && cb.call(this,e);
            }.bind(this), false)
        }
    }

    Scroller.defaultOptions = {
        parentNode: null,
        ulNode: null,
        itemNodes: null,
        time: 0.3,
        ativeClass: null
    }

    window.Scoller = Scroller;

})(window)

相关文章

网友评论

      本文标题:js封装tab可滑动到中间位置

      本文链接:https://www.haomeiwen.com/subject/kibncrtx.html