封装使用(插件,兼容等)

场景:弹出短的提示信息;  

场景:出现弹框展示短的提示信息,并且出现显示的倒计时 2s 后,弹框消失,整体框架用的是jquery-weui,本来想直接用toast,但是好像不能显示倒计时。

场景:分享的功能只有在微信打开网页有,那么,引导分享的按钮只能在微信网页里有效(或显示)

场景:页面滚动到距离底部一定的距离,发生了什么???

场景:倒计时 还剩多少

场景:原生js获取样式

场景:银行账号(4位分割)

场景:需要使用原生javascript添加事件

场景:阻止冒泡和默认事件

场景:从location中获取数据;

场景:去抖和节流

 

 

场景:弹出短的提示信息;(10.27完善)

ipop-layer.js

/**
 * Created by Administrator on 2017/10/26 0026.
 */
var popLayer = {
    init (option) {
        //合并参数
        this.initOptions(option);
        //初始化html
        this.initElement(option);
        document.getElementsByClassName("j-pop-close-btn")[0].onclick = () => {
            this.closeLayer()
        };
        //回调
        this.ensuerFunc();
        this.cancelFunc();
    },
    option: {
        title: "提示",         //弹窗标题
        state: "warning",     //状态
        text: "",              //文本
        showCancel: false,    //显示取消按钮
        ensuerFunc: "",       //确定按钮  回调
        cancelFunc: "",       //取消按钮  回调
        ensuerText: "确定",  //确定按钮文本
        cancelText: "取消",  //取消按钮文本
        basePath: ""
    },
    initStateSrc(state){
        switch (state) {
            case "error":
                this.state = this.basePath + state;
                break;
            case "success":
                this.state = this.basePath + state;
                break;
            case "warning":
                this.state = this.basePath + state;
                break;
            default:
                "warning";
        }
    },
    initOptions(option){
        option = Object.assign(this.option, option);
    },
    closeLayer(){
        document.getElementsByClassName("j-pop1")[0].parentNode.removeChild(document.getElementsByClassName("j-pop1")[0]);
    },
    ensuerFunc(){
        document.getElementsByClassName("ensuer")[0].onclick = () => {
            return this.option.ensuerFunc();
        };
    },
    cancelFunc(){
        document.getElementsByClassName("cancel")[0].onclick = () => {
            return this.option.cancelFunc();
        };
    },
    initElement(option){
        this.initStateSrc(option.state);
        var ele = `<div style="display: table-cell;vertical-align: middle;text-align: center">
                        <div class="j-pop-cont">
                                <div class="j-pop-cont-title">
                                    <span class="j-pop-title-text">${this.option.title}</span>
                                </div>
                                <div class="j-pop-close-btn">
                                       ×
                                </div>
                                <div class="j-pop-cont-detail">
                                    <div class="j-pop-state-icon">
                                        ${this.option.state}
                                    </div>
                                    <div class="j-pop-txt">
                                        <span class="text">${this.option.text}</span>
                                    </div>
                                </div>
                                <div class="j-pop-btn">
                                        <span class="cancel" style="display: ${this.option.showCancel === false ? "none" : ""}">
                                            ${this.option.cancelText}
                                        </span>
                                        <span class="ensuer">${this.option.ensuerText}</span>
                                    </div>
                            </div>
                        </div>
                    </div>`;
        var createElement = document.createElement("div");
        createElement.className = "j-pop1";
        createElement.innerHTML = ele;
        document.body.appendChild(createElement);
    },
};

 

index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>弹框</title>
    <link rel="stylesheet" href="pop-layer.css">
</head>
<body>
<button>弹框</button>
<script src="polyfill.min.js"></script>
<script src="pop-layer-compile.js"></script>
<script>
    document.getElementsByTagName("button")[0].onclick = function () {
        var layerOptions = {
            title: "提示",            //弹窗标题
            state: "error",        //状态
            text: "測試文字",      //文本 也可以是html
            showCancel: true,       // 显示取消按钮
            ensuerFunc: ensuerFunc, //确定按钮  回调
            cancelFunc: cancelFunc, //取消按钮  回调
            ensuerText: "确定",     //确定按钮文本
            cancelText: "取消",       //取消按钮文本
        };
        popLayer.init(layerOptions);
    };
    var ensuerFunc = () => {
        popLayer.closeLayer();
        console.log("ensuerFunc");
    };
    var cancelFunc = () => {
        popLayer.closeLayer();
        console.log("cancelFunc");
    }
</script>
</body>
</html>
View Code

重写同事200+的弹出插件;state改为图片路径更好。使用的版本有需要自己改。需要兼容使用babel转一下。

基础样式

.j-pop1 {
  width: 100%;
  height: 100%;
  position: fixed;
  top:0;
  left:0;
  display: table;
  font-size: 14px;
  background: rgba(0, 0, 0, .4);
  line-height: 30px;
  .j-pop-cont {
    border-radius: 4px;
    text-align: left;
    background: #fff;
    display: inline-block;
    padding-bottom:0.1px;
    &-title {
      padding: 10px;
      font-weight: bold;
      border-bottom: 1px solid #dcdcdc;
      background: #f5f5f5;
    }
    &-detail {
      padding: 20px 10px 30px 10px;
      font-size: 0;
      .j-pop-state-icon {
        vertical-align: middle;
        width: 60px;
        height: 60px;
        display: inline-block;
        background: #f60;
        border-radius: 100%;
        margin-right: 10px;
      }
      .j-pop-txt {
        display: inline-block;
        font-size: 12px;
        width: 210px;
        vertical-align: middle;
      }
    }
    .j-pop-close-btn {
      position: absolute;
      right: 10px;
      top: 10px;
      font-size: 20px;
      cursor: pointer;
      width: 30px;
      height: 30px;
    }
  }
  .j-pop-btn {
    text-align: right;
    line-height: 36px;
    margin-right: 10px;
    font-size: 0;
    padding-bottom: 20px;
    span {
      display: inline-block;
      vertical-align: middle;
      width: 96px;
      height: 36px;
      border-radius: 18px;
      text-align: center;
      font-size: 12px;
      cursor: pointer;
    }
    .cancel {
      background: #f5f5f5;
      border: 1px solid #dcdcdc;
    }
    .ensuer {
      background: #f60;
      color: #fff;
      margin-left: 20px;
    }
  }
}
View Code

 

场景:出现弹框展示短的提示信息,并且出现显示的倒计时 2s 后,弹框消失,整体框架用的是jquery-weui,本来想直接用toast,但是好像不能显示倒计时。(10.27完善)


/**
* Created by Administrator on 2017/10/27 0027.
*/
function BallWithTime(_time, _txt, callBack) {
var time = _time;
var _childNode = document.createElement("div");
_childNode.className = "pop-reverse";
_childNode.style.display = "table";
var _html = `<div class='pop-reverse-content'>
<div class="pop-rc-inner">
<p class="pop-rc-inner-txt">${_txt}</p>
<p id='time_out' class="pop-rc-inner-time">${time}s</p>
</div>
</div>`;
_childNode.innerHTML = _html;
document.body.appendChild(_childNode);
var _timeOut = setInterval(function () {
if (time == 0) {
document.body.removeChild(_childNode);
clearInterval(_timeOut);
if (callBack && typeof callBack == "function") {
callBack()
}
} else {
time = time - 1;
document.getElementById("time_out").innerHTML = `${time}s`
}
}, 1000)
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="pop-tip.css">
</head>
<body>'

<script src="pop-tip-compile.js"></script>
<script>
    function cb() {
        alert("成功")
    }
    BallWithTime(3, "测试文字", cb)
</script>
</body>
</html>
View Code

基本样式

.pop-reverse {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  font-size: 14px;
  line-height: 24px;
  .pop-reverse-content {
    display: table-cell;
    vertical-align: middle;
    text-align: center
  }
  .pop-rc-inner {
    display: inline-block;
    padding: 10px 25px;
    width: 160px;
    font-size: 14px;
    background: rgba(0, 0, 0, 0.4);
    border-radius: 4px;
    &-txt {
      text-align: left;
      font-size: 14px;
    }
    &-time {
      text-align: center;
      font-size: 12px;
    }
  }
}
View Code

 

场景:分享的功能只有在微信打开网页有,那么,引导分享的按钮只能在微信网页里有效(或显示)(无依赖)

var _weixin = false;
function is_weixin() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        _weixin = true;
    }
}

 

场景:页面滚动到距离底部一定的距离,发生了什么???

//callBack1,callBack2 回调函数
//dis distance 距离底部的距离
function
scrollWatcher(callback1, callback2, dis) { var _height = $(window).height(); $(window).scroll(function () { if ($(window).scrollTop() > _height - dis && callback1 && typeof callback1 == "function") { callback1() } else if ($(window).scrollTop() <= _height - dis && callback2 && typeof callback2 == "function") { callback2() } }) }

 场景:倒计时 还剩多少

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>javascript倒计时</title>
</head>
<body>
<div id="count-down1"></div>
<script>
//版本:还剩多少天
//60*60*24:86400
function Countdown(data, id) {
var _timeStamp_target = new Date(data).getTime();
var _timeStamp_now_test = new Date().getTime();
var _setInterval = setInterval(function () {
var _timeStamp_now = new Date().getTime();
var _timeStamp_warp = Math.floor((_timeStamp_target - _timeStamp_now) / 1000);
var _day_test = Math.floor(_timeStamp_warp / 86400);
var _day = _day_test <= 9 ? "0" + _day_test + '<span class="time">天</span>' : _day_test + '<span class="time">天</span>';
var _hour_test = Math.floor((_timeStamp_warp % 86400) / 3600);
var _hour = _hour_test <= 9 ? "0" + _hour_test + '<span class="time">小时</span>' : _hour_test + '<span class="time">小时</span>';
var _minite_test = Math.floor((_timeStamp_warp % 86400 % 3600) / 60);
var _minite = _minite_test <= 0 ? "0" + _minite_test + '<span class="time">分钟</span>' : _minite_test + '<span class="time">分钟</span>';
var _minite_test = Math.floor(_timeStamp_warp % 86400 % 3600 % 60);
var _second = _minite_test <= 9 ? "0" + _minite_test + '<span class="time">秒</span>':_minite_test + '<span class="time">秒</span>';
var _timeStr = _day + _hour + _minite + _second;
document.getElementById(id).innerHTML = _timeStr;
if(!_timeStamp_warp){
clearInterval(_setInterval);
return
}
}, 1000);
}
Countdown("2017/10/27 23:06:00", "count-down1")
</script>
</body>
</html>

 场景:原生js获取样式

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div></div>
<script>
function getStyle(element, attr) {
var value;
if (typeof window.getComputedStyle != 'undefined') {
value = window.getComputedStyle(element, null)[attr];
} else if (typeof element.currentStyle != 'undefined') {
value = element.currentStyle[attr];
}
return value;
}
var div = document.getElementsByTagName("div")[0];
var style = getStyle(div,"backgroundColor");
console.log(style)
</script>
</body>
</html>
  • dom.style[attr]只能获取标签内联样式

  • IE下: oDiv.currentStyle[attr]

  • Chrome,FF下: getComputedStyle(oDiv,null)[attr]

  • 复合属性写法:如实例

 场景:银行账号

function bankCodeFormat(id) {
    var just_changed = true;
    var btnObj = document.getElementById(id);

    function format() {
        if (just_changed) {
            just_changed = false;
            var v = btnObj.value.replace(/\D/g, "");
            if (/\S{5}/.test(v)) {
                btnObj.value = v.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
            } else {
                btnObj.value = v;
            }
        }
        just_changed = true;
    }

    if (btnObj.addEventListener) {
        btnObj.addEventListener("input", format, false);
    } else if (btnObj.attachEvent) {
        btnObj.attachEvent("onpropertychange", format) //兼容IE8
    } else {
        console("error")
    }
}

jq做了很多事情,会让使用者不易真正了解属性的含义,就如propertychange。。。

场景:需要使用原生javascript添加事件

function addEventHandler(target, type, func) {
    if (target.addEventListener) {    //监听IE9,谷歌和火狐
        target.addEventListener(type, func, false);
    } else if (target.attachEvent) {
        target.attachEvent("on" + type, func);
    }
}

 场景:阻止冒泡和默认事件

window.event? window.event.cancelBubble = true : e.stopPropagation();
window.event? window.event.returnValue = false : e.preventDefault();

 整理使用:

<div class="box">
    <div class="box2">
        <div class="box3"></div>
    </div>
</div>
<script>
    function addEventHandler(target, type, func) {
        if (target.addEventListener) {    //监听IE9,谷歌和火狐
            target.addEventListener(type, func, false);
        } else if (target.attachEvent) {
            target.attachEvent("on" + type, func);
        }
    }
    function getClass(_class) {
        return document.getElementsByClassName(_class)[0];
    }
    function boxClick() {
        window.event ? window.event.cancelBubble = true : e.stopPropagation();
        var boxClassName = event.srcElement ? event.srcElement.className : event.target.className;
        alert(boxClassName)
    }
    addEventHandler(getClass("box1"), "click", boxClick);
    addEventHandler(getClass("box2"), "click", boxClick);
    addEventHandler(getClass("box3"), "click", boxClick);
</script>

 场景:从location中获取数据(12.26)

从一个项目中跳链接过来的,直接从链接中获取参数然后在请求别的数据,页面跳转也是路由带参,完全的前后端分离。

function getUrlParms() {
        var url = location.search;
        var Request = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1); //去掉?号
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                Request[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
            }
            return Request
        }
    }

没使用正则而是最简单的字符串方法,简单易懂好用~~~~

20180428 阅读了这篇文章,我的思想真是漏洞百出 ,怕是过不了面试了。

场景:去抖和节流

function debounce(fn, delay) {
        var timer = null;
        return function () {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(context, args);
            }, delay);
        };
    }

function throttle(fn, threshhold, scope) {
        threshhold || (threshhold = 250);
        var last,
            timer;
        return function () {
            var context = scope || this;
            var now = +new Date(),
                args = arguments;
            if (last && now - last + threshhold < 0) {
                clearTimeout(deferTimer);
                timer = setTimeout(function () {
                    last = now;
                    fn.apply(context, args);
                }, threshhold);
            } else {
                last = now;
                fn.apply(context, args);
            }
        };
    }

  

posted @ 2017-09-22 10:02  Merrys  阅读(273)  评论(0编辑  收藏  举报