js封装插件【组件】三种方式,含es6新特性。

1.先来说一下我使用到的es6的Object.assign。在jq里合并对象用的是extend方法,用来处理默认参数和传入参数做合并。es6里为我们提供了Object.assign,但是ie下全部撂倒。

解决办法:在使用Object.assign之前,写下:

if (!Object.assign) {
            Object.defineProperty(Object, "assign", {
              enumerable: false,
              configurable: true,
              writable: true,
              value: function(target, firstSource) {
                "use strict";
                if (target === undefined || target === null)
                  throw new TypeError("Cannot convert first argument to object");
                var to = Object(target);
                for (var i = 1; i < arguments.length; i++) {
                  var nextSource = arguments[i];
                  if (nextSource === undefined || nextSource === null) continue;
                  var keysArray = Object.keys(Object(nextSource));
                  for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                    var nextKey = keysArray[nextIndex];
                    var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                    if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
                  }
                }
                return to;
              }
            });
          }

  

2.第一种,面向对象写法-挂载到window下

(function(win, doc) {
    var defaultSettings = {
        /* color: "red",
        background: "blue",
        border: "2px solid #000",
        fontSize:"30px",
        textAlign:"center",
        width:"200px",
        borderRadius:"5px" */
    };

    function SetStyles(options) {
        var self = this;
    
        //没传配置项自己丢错
        if(!options) {
            throw new Error("请传入配置参数");
        }
        if (!Object.assign) {
            Object.defineProperty(Object, "assign", {
              enumerable: false,
              configurable: true,
              writable: true,
              value: function(target, firstSource) {
                "use strict";
                if (target === undefined || target === null)
                  throw new TypeError("Cannot convert first argument to object");
                var to = Object(target);
                for (var i = 1; i < arguments.length; i++) {
                  var nextSource = arguments[i];
                  if (nextSource === undefined || nextSource === null) continue;
                  var keysArray = Object.keys(Object(nextSource));
                  for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                    var nextKey = keysArray[nextIndex];
                    var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                    if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
                  }
                }
                return to;
              }
            });
          }
        self = Object.assign(self, defaultSettings, options);

        self.container = doc.querySelector(self.container) || doc.querySelectorAll(self.container);
        self.init();
        
    }

    SetStyles.prototype = {
        /* _changeStyles: function() {            
            var self = this;
            for(var pro in self) {
                if(pro == "container") {
                    continue;
                }
                if(pro == 'text' && typeof self[pro]== 'string') {
                    self.container.innerText = self[pro];
                    continue;
                }else if(pro == 'text' && typeof self[pro]== 'function'){
                    self.container.innerText = self[pro]();
                    continue;
                }
                self.container.style[pro] = self[pro];
            }
        }, */
        appendCss:function(){
            var link=document.createElement('link');
            link.href="./index.css";
            link.type='text/css';
            link.rel = 'stylesheet';
            document.querySelector("head").appendChild(link);
        },
        appendHtml:function(){
            var htmlin='
'+ '

我是内容

'+'
'; var html=document.createElement("div"); html.innerHTML=htmlin; document.querySelector("body").appendChild(html); }, init:function(){ this.appendCss(); this.appendHtml(); } } win.SetStyles = SetStyles; })(window, document) //调用: new SetStyles({ container:"#box", background:"#fff", textAlign:"center", text:function(){ return "我是文本"; } });

  

第二种:面向对象方法【推荐】

"use strict";
class websong{       
    constructor(opt){
       const ops={
            el:"",
            css:"./class.css"
        }
        this.ops=Object.assign({},ops,opt)
    }
    appendCss(){
        var thas=this;
        var link=document.createElement("link");
        link.href=thas.ops.css;
        link.type='text/css';
        link.rel = 'stylesheet';
        link.setAttribute("id","main")
        document.querySelector("head").appendChild(link);
        
      /* return link.onload = link.readystatechange = function () {  
            if (!link.readyState || /loaded|complete/.test(link.readyState)) {                                               
                //开始回调
                link.onload = link.readystatechange = null;                
            }
        }   */

    }
    appendHtml(){        
        var thmlin='
标题【关闭】

我是生成的内容

'; var html=document.createElement("div"); html.setAttribute("id","openBoxContainer"); html.className="hide"; html.innerHTML=thmlin; document.querySelector("body").appendChild(html); var showdin="
"; var showd=document.createElement("div"); showd.innerHTML=showdin; document.querySelector("body").appendChild(showd); } evnet(){ var thas=this; var el; if((thas.ops.el).match(/[#.]/)){ el=document.querySelector(thas.ops.el); if(!el){ return console.log("你传入的el没有查找到") } el.οnclick=open; }else{ el=document.querySelectorAll(thas.ops.el); if(el.length==0){ return console.log("你传入的el没有查找到") } for(var i=0;i ww ? demoX = ww - ow : ""; var wh=window.innerHeight; var oh=demo.offsetHeight; demoY<0?demoY=0:""; demoY+oh>wh?demoY=wh-oh:''; // 鼠标移动时demo的位置坐标 demo.style.left = demoX + "px"; demo.style.top = demoY + "px"; //清除选中文字 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } }; // 鼠标抬起清除拖拽效果 document.onmouseup = function () { document.onmousemove = null; }; // 点击关闭按钮关闭跟随框 close.onclick = function () { this.parentNode.parentNode.className="hide"; }; })(window) } } init(){ var thas=this; thas.appendCss();thas.appendHtml();thas.evnet() return thas; } } new websong({ "el":"#box" }).init();

  

3.弹窗插件【网友的】借鉴其思路

(function(window,document){  
    var MaskShare = function(targetDom,options){  
        // 判断是用函数创建的还是用new创建的。这样我们就可以通过MaskShare("dom") 或 new MaskShare("dom")来使用这个插件了  
        if(!(this instanceof MaskShare))return new MaskShare(targetDom,options);  

        // 参数合并  
        this.options = this.extend({  
                        // 这个参数以后可能会更改所以暴露出去  
            imgSrc:"../static/img/coupon-mask_1.png"  
        },options);  
  
        // 判断传进来的是DOM还是字符串  
        if((typeof targetDom)==="string"){  
            this.targetDom = document.querySelector(targetDom);  
        }else{  
            this.targetDom = targetDom;  
        }  
  
        var boxDom = document.createElement("div");  
        var imgDom = document.createElement("img");  
  
        // 设置默认样式 注意将z-index值设置大一些,防止其他元素层级比遮罩层高  
        boxDom.style.cssText = "display: none;position: absolute;left: 0;top: 0;width: 100%;height:100%;background-color: rgba(0,0,0,0.8);z-index:9999;";  
        imgDom.style.cssText = "margin-top:20px;width: 100%;";  
  
        // 追加或重设其样式  
        if(this.options.boxDomStyle){  
            this.setStyle(boxDom,this.options.boxDomStyle);  
        }  
        if(this.options.imgDomStyle){  
            this.setStyle(imgDom,this.options.imgDomStyle);  
        }  
  
        imgDom.src = this.options.imgSrc;  
        boxDom.appendChild(imgDom);  
        this.boxDom = boxDom;  
  
        // 初始化  
        this.init();  
    };  
    MaskShare.prototype = {  
        init:function(){  
            this.event();  
        },  
        extend:function(obj,obj2){  
            for(var k in obj2){  
                obj[k] = obj2[k];  
            }  
            return obj;  
        },  
        setStyle:function(dom,objStyle){  
            for(var k in objStyle){  
                dom.style[k] = objStyle[k];  
            }  
        },  
        event:function(){  
            var _this = this;  
  
            this.targetDom.addEventListener("click",function(){  
                document.body.appendChild(_this.boxDom);  
                _this.boxDom.style.display = "block";  
                                // 打开遮罩层的回调  
                _this.options.open&&_this.options.open();  
            },false);  
  
            this.boxDom.addEventListener("click",function(){  
                this.style.display = "none";  
                                // 关闭遮罩层的回调  
                _this.options.close&&_this.options.close();  
            },false);  
        }  
    };  
    // 暴露方法
    window.MaskShare = MaskShare;  
}(window,document));  

  

new MaskShare("#openBtn",{
imgSrc:"http://image.tupian114.com/20180322/2109277031.jpg",
boxDomStyle:{
opacity:".9"
},
imgDomStyle:{
opacity:".8"
},
open:function(){
console.log("show");
},
close:function(){
console.log("close");
}
});

 

转载于:https://www.cnblogs.com/webSong/p/8643507.html

你可能感兴趣的:(js封装插件【组件】三种方式,含es6新特性。)