zoukankan      html  css  js  c++  java
  • JavaScript代码片段

    ajax请求

    /*
        ajax 方法
        参数
            url: 请求的资源url
            fnSucc: 当结果返回时调用的方法,参数为结果文本
            fnFaild: 当相应异常时调用的方法,可以不给
    */
    function ajax(url, fnSucc, fnFaild){
        var xmlHttp = null;
        // 创建ajax 对象
        if(window.XMLHttpRequest){
            xmlHttp = new XMLHttpRequest();
        }else{
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") || new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.open('GET', url, true);
        // 发送请求
        xmlHttp.send(null);
        // ajax状态
        xmlHttp.onreadystatechange = function(){
            // 通信完成
            if(xmlHttp.readyState == 4){
                // 是否成功
                if(xmlHttp.status == 200){
                    fnSucc(xmlHttp.responseText);
                }else{
                    if(fnFaild){
                        fnFaild();
                    }
                }
            }
        }
    }

    获取元素最终样式

    /*
        可以获取元素的最终样式
        参数: 
            obj: 元素(Element)
            attr: 属性名
    */
    function getStyle(obj, attr){
        if(obj.currentStyle){
            return obj.currentStyle[attr];
        }
        else{
            return getComputedStyle(obj, false)[attr];
        }
    }

    获取或设置css属性

    /*
        设置或返回css属性
        可以连续调用,例: css(div,'width',100)('height',200);
        参数:
            obj: 元素
            attr: 属性名
            value: 要设置的值,无需单位,若不设置不给即可
    */
    function css(obj, attr, value){
        // 当参数为两个是返回属性值
        if(arguments.length==2){
            if(attr=="transform"){
                return obj.transform;
            }
            var i=parseFloat(obj.currentStyle?obj.currentStyle[attr]:document.defaultView.getComputedStyle(obj, false)[attr]);
            var val=i?i:0;
            if(attr=="opacity"){
                val*=100;
            }
            return val;
        // 当参数为三个时设置属性
        }else if(arguments.length==3){
            switch(attr){
                case 'width':
                case 'height':
                case 'paddingLeft':
                case 'paddingTop':
                case 'paddingRight':
                case 'paddingBottom':
                    value=Math.max(value,0);
                case 'left':
                case 'top':
                case 'marginLeft':
                case 'marginTop':
                case 'marginRight':
                case 'marginBottom':
                    obj.style[attr]=value+'px';
                    break;
                case 'opacity':
                    if(value<0){
                        value=0;
                    }
                    obj.style.filter="alpha(opacity:"+value+")";
                    
                    obj.style.opacity=value/100;
                    break;
                case 'transform':
                    obj.transform=value;
                    obj.style["transform"]="rotate("+value+"deg)";
                    obj.style["MsTransform"]="rotate("+value+"deg)";
                    obj.style["MozTransform"]="rotate("+value+"deg)";
                    obj.style["WebkitTransform"]="rotate("+value+"deg)";
                    obj.style["OTransform"]="rotate("+value+"deg)";
                break;
                default:
                    obj.style[attr]=value;
            }
            return function (attr_in, value_in){
                css(obj, attr_in, value_in)
            };
        }
    }

    阻止右键菜单

    /*
        阻止右键菜单
    */
    function stopRightMenu(){
        document.oncontextmenu=function(){
            return false;
        }
    }

    运动函数

    /*
    实现div随鼠标拖拽(面对对象的)
                function Drag(id)
            实现div随鼠标拖拽
                function drag(id)
            实现div随鼠标拖拽,限制在窗口内(面对对象)
                function LimitDrag(id)
            元素运动
                function startMove(obj, oTarget, iType, fnCallBack, fnDuring)
            元素停止运动
                function stopMove(obj)
    */
    
    
    
    /*
        实现div随鼠标移动实现拖拽效果
        div需指定宽高, position:absolute;
        参数:
            id: div的id
        示例: 
            new Drag('div1');
    */
    function Drag(id){
        var _this=this;
        
        this.disX=0;
        this.disY=0;
        this.oDiv=document.getElementById(id);
        // 鼠标在div中按下,调用方法
        this.oDiv.onmousedown=function ()    {
            _this.fnDown();
        };
    }
    // 鼠标按下时调用的方法
    Drag.prototype.fnDown=function (ev){
        var _this=this;
        var oEvent=ev||event;
        // 保存鼠标在div的位置
        this.disX=oEvent.clientX-this.oDiv.offsetLeft;
        this.disY=oEvent.clientY-this.oDiv.offsetTop;
        
        document.onmousemove=function (){
            _this.fnMove();
        };
        
        document.onmouseup=function (){
            _this.fnUp();
        };
        // 阻止默认事件,防止移动过程中会选中内容
        oEvent.preventDefault();
    };
    // 鼠标移动时调用的方法
    Drag.prototype.fnMove=function (ev){
        var oEvent=ev||event;
        // 修改div的位置
        this.oDiv.style.left=oEvent.clientX-this.disX+'px';
        this.oDiv.style.top=oEvent.clientY-this.disY+'px';
    };
    // 鼠标松开时调用的方法
    Drag.prototype.fnUp=function (){
        document.onmousemove=null;
        document.onmouseup=null;
    };
    
    /*
        实现div随鼠标移动实现拖拽效果
        div需指定宽高, position:absolute;
        参数:
            id: div的id
        示例: 
            drag('div1');
    */
    function drag(id){
        var div = document.getElementById(id);
        div.onmousedown = function(ev){
            var oEvent = ev||event;
            // 板寸鼠标与div的相对位置
            var disX = oEvent.clientX-div.offsetLeft;
            var disY = oEvent.clientY-div.offsetTop;
            // 鼠标移动
            document.onmousemove = function(ev){
                var oEvent = ev||event;
                div.style.left = oEvent.clientX-disX + 'px';
                div.style.top = oEvent.clientY-disY + 'px';
            };
            document.onmouseup = function(){
                document.onmousemove = null;
                document.onmouseup = null;
            }
            oEvent.preventDefault();
        };
        
    }
    
    
    
    
    
    /*
        实现div随鼠标移动实现拖拽效果, 会限制移动范围,防止移出窗口, 继承了 Drag 类
        div需指定宽高, position:absolute;
        参数:
            id: div的id
        示例: 
            new LimitDrag('div1');
    */
    function LimitDrag(id){
        Drag.call(this, id);
    }
    
    for(var i in Drag.prototype){
        LimitDrag.prototype[i]=Drag.prototype[i];
    }
    // 重写父类的移动方法,使其不会移出窗口
    LimitDrag.prototype.fnMove=function (ev){
        var oEvent=ev||event;
        var l=oEvent.clientX-this.disX;
        var t=oEvent.clientY-this.disY;
        
        if(l<0){
            l=0;
        }
        else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){
            l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
        }
        
        if(t<0){
            t=0;
        }
        else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight){
            t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
        }
        
        this.oDiv.style.left=l+'px';
        this.oDiv.style.top=t+'px';
    };
    
    
    
    // 定义类型,运动用
    var MOVE_TYPE={
        BUFFER: 1,    /*缓冲运动*/
        FLEX: 2            /*温柔的运动,嘿嘿*/
    };
    /*
        运动的函数,可以自定义元素状态改变方式
        参数: 
            obj: 元素
            oTarget: css参数   {300}
            iType: 运动类型 MOVE_TYPE 中的元素, 默认缓冲运动
            fnCallBack: 运动停止时调用的函数, 可以不给
            fnDuring: 运动中调用的函数,即css属性每改变一次就调用, 可以不给
    */
    function startMove(obj, oTarget, iType, fnCallBack, fnDuring){
        var fnMove=null;
        if(obj.timer){
            clearInterval(obj.timer);
        }
        
        switch(iType){
            case MOVE_TYPE.BUFFER:
                fnMove=doMoveBuffer;
                break;
            case MOVE_TYPE.FLEX:
                fnMove=doMoveFlex;
                break;
            default: 
                fnMove=doMoveBuffer;
        }
        
        obj.timer=setInterval(function (){
            fnMove(obj, oTarget, fnCallBack, fnDuring);
        }, 30);
    }
    /*
        停止运动
        参数:
            obj: 运动的元素
    */
    function stopMove(obj){
        // 清除定时器
        clearInterval(obj.timer);
    }
    // 缓冲运动函数
    function doMoveBuffer(obj, oTarget, fnCallBack, fnDuring){
        // 是否停止
        var bStop=true;
        var attr='';
        // 定义速度
        var speed=0;
        var cur=0;
        // 进行运动
        for(attr in oTarget){
            cur=css(obj, attr);
            if(oTarget[attr]!=cur){
                bStop=false;
                
                speed=(oTarget[attr]-cur)/5;
                speed=speed>0?Math.ceil(speed):Math.floor(speed);
                
                css(obj, attr, cur+speed);
            }else{
                bSop=false;
            }
        }
        // 调用运动中函数
        if(fnDuring)fnDuring.call(obj);
        
        if(bStop){
            clearInterval(obj.timer);
            obj.timer=null;
            
            if(fnCallBack)fnCallBack.call(obj);
        }
    }
    // 温柔的运动函数
    function doMoveFlex(obj, oTarget, fnCallBack, fnDuring){
        var bStop=true;
        var attr='';
        // 定义速度
        var speed=0;
        var cur=0;
        
        for(attr in oTarget){
            if(!obj.oSpeed)obj.oSpeed={};
            if(!obj.oSpeed[attr])obj.oSpeed[attr]=0;
            cur=css(obj, attr);
            if(Math.abs(oTarget[attr]-cur)>=1 || Math.abs(obj.oSpeed[attr])>=1){
                bStop=false;
                
                obj.oSpeed[attr]+=(oTarget[attr]-cur)/5;
                obj.oSpeed[attr]*=0.7;
                
                css(obj, attr, cur+obj.oSpeed[attr]);
            }
        }
        
        if(fnDuring)fnDuring.call(obj);
        
        if(bStop){
            clearInterval(obj.timer);
            obj.timer=null;
            
            if(fnCallBack)fnCallBack.call(obj);
        }
    }

    字符串函数

    /*
        去除字符串两边的空格
    */
    function delStrSpace(str){
        return str.replace( /^(s|u00A0)+|(s|u00A0)+$/g, "" );//正则替换
    }
    
    /*
        验证字符串是否为空(会去除两边的空格)
    */
    function isNull(str){
        if(!delStrSpace(str)){
            return true;
        }else{
            return false;
        }
    }
    /*
        关键词高亮显示
        参数:
            e: 元素,如 p标签等
            keys: 关键词数组
            color: 显示的颜色,默认黑色
    */
    function keyWordsHighlight(e, keys, color){
        var
            i = 0,
            l = keys.length,//关键词的长度
            k = "";
        for(; i < l ; i++){
            k = keys[i];//获取关键词的对象
            //替换关键词的数据
            e.innerHTML = e.innerHTML.replace(k, "<span style='color:"+ (color || "#000")+"'>" + k + "</span>")
        }
    }

    时间函数

    /*
        返回当前时间字符串(无参或只传一个参数,会使用中文分割)
        参数:
            a: 分割年月日的符号
            b: 分割时分秒的符号
    */
    function getNowTimeStr(a, b){
        var date =new Date();//获取日期对象
        
        if(a && b){
            return date.getFullYear() + a
                    + (date.getMonth() + 1) + a
                    + date.getDate()
                    + " "
                    + date.getHours() + b
                    + date.getMinutes() + b
                    + date.getSeconds();
            
        }else{
            /*获取年、月、日、时、分、秒,本地系统的时间*/
            return date.getFullYear() + "年"
                    + (date.getMonth() + 1) + "月"
                    + date.getDate() + "日"
                    + " "
                    + date.getHours() + "时"
                    + date.getMinutes() + "分"
                    + date.getSeconds() + "秒";
        }
        
    }
    
    /*
        返回到指定日期还剩多少天,数字
        参数:
            Y: 年(默认0)
            M: 月(默认0)
            D: 日(默认0)
            h: 时(默认0)
            m: 分(默认0)
            s: 秒(默认0)
    */
    function getCountDown(Y, M, D, h, m, s){
        Y = Y || 0;
        M = M || 0;
        D = D || 0;
        h = h || 0;
        m = m || 0;
        s = s || 0;
        var date = new Date(Y, M-1, D, h, m, s),
        //转换为时间戳,方便计算差值
        times = date.getTime() - new Date().getTime();
        //返回天数
        return Math.ceil(times / (1000 * 60 * 60 * 24));
    }

    展示toast

        /**
         * 显示toast
         * @param params
         * 设置参数
         * {
         *     'text': '显示内容', str
         *     'time': 显示时间,默认2s, int
         *     'color': 字体颜色,默认白色, str
         *     'background-color': toast背景色,默认黑色,50透明度, str
         *     'is-full': 是否布满屏幕,布满时内容不可点击, 默认布满, bool
         *     'location': 显示位置, top,center,bottom, 默认center, str
         * }
         */
        function toast(params) {
            if(params['text'] == null){
                return;
            }
            // 给参数赋默认值
            params['time'] = params['time'] == null ? 2000 : params['time'] * 1000;
            params['color'] = params['color'] == null ? '#FFFFFF' : params['color'];
            params['background-color'] = params['background-color'] == null ? 'rgba(0,0,0,0.50)' : params['background-color'];
            params['is-full'] = params['is-full'] == null ? true : params['is-full'];
            params['location'] = params['location'] == null ? 'center' : params['location'];
            // 若未添加div, 则添加
            if(document.getElementById('toast_text') == null){
                createToastDiv(params);
            }
            document.getElementById('toast_text').innerHTML = params['text'];
            document.getElementById('toast_pop').style.display = 'block';
            setTimeout(function() {
                document.getElementById('toast_pop').style.display = 'none';
            }, params['time']);
        }
    
        // 创建toast div并添加到body中
        function createToastDiv(params) {
            var toastPop = document.createElement('div');
            var toastInner = document.createElement('div');
            var toastText = document.createElement('p');
    
            // 设置各个div的css属性
            // 设置是否需要div布满窗口
            if(params['is-full']){
                toastPop.style.display = 'block';
                toastPop.style.position = 'fixed';
                toastPop.style.width = '100%';
                toastPop.style.top = '0';
                toastPop.style.left = '0';
                toastPop.style.bottom = '0';
                toastPop.style.right = '0';
                toastPop.style.textAlign = 'center';
                toastPop.style.zIndex = '9999';
            }
            toastPop.id = 'toast_pop';
            toastInner.style.position = 'fixed';
            toastInner.style.maxWidth = '100%';
            toastInner.style.left = '50%';
            // 设置div的上中下位置
            if(params['location'] === 'top'){
                toastInner.style.top = '0px';
                toastInner.style.transform = 'translate(-50%,0)';
            }else if(params['location'] === 'bottom'){
                toastInner.style.bottom = '0px';
                toastInner.style.transform = 'translate(-50%,0)';
            }else{
                toastInner.style.top = '50%';
                toastInner.style.transform = 'translate(-50%,-50%)';
            }
            toastInner.style.textAlign = 'center';
            toastText.style.display = 'inline-block';
            toastText.style.padding = '20px 20px';
            toastText.style.fontSize = '3em';
            toastText.style.maxWidth = '90%';
            toastText.style.wordWrap = 'break-word';
            toastText.style.color = params['color'];
            toastText.style.borderRadius = '3ch';
            toastText.style.backgroundColor = params['background-color'];
            toastText.id = 'toast_text';
            // 将元素插入
            toastInner.appendChild(toastText);
            toastPop.appendChild(toastInner);
            window.document.body.appendChild(toastPop);
        }

    展示input file标签上传的图片

        /**
         * 修改标签的src属性, 使用input file
         * 通常用来展示上传图片
         * @param srcId
         * src展示id
         * @param inputId
         * file input标签id
         */
        function changeInputToSrc(srcId, inputId) {
            document.getElementById(inputId).onchange = function () {
                var preview = document.getElementById(srcId);
                var file    = document.getElementById(inputId).files[0];
                var reader  = new FileReader();
                reader.onloadend = function () {
                    preview.src = reader.result;
                };
                if (file) {
                    reader.readAsDataURL(file);
                } else {
                    preview.src = "";
                }
            };
        }

    多选框的全选事件

    /**
     * 用户多选框的全选事件
     * @param name
     * input 的name值
     * @param allVal
     * 全选按钮的value
     */
    function checkboxCheckAll(name, allVal) {
        var checkbox = "input[name='" + name + "']";
        // 为复选框添加改变时间, 全渠道全选
        $(checkbox).change(function () {
            // 若全渠道选中, 将所有勾选
            if($(this).val() == allVal && $(this).is(':checked')){
                $(checkbox).prop("checked", 'checked');
                // 若全渠道取消选中, 将所有取消勾选
            }else if($(this).val() == allVal && !$(this).is(':checked')){
                $(checkbox).prop("checked", '');
                // 若其他选中, 判断是否全部选中, 若是,将全渠道勾选
            }else if($(this).val() != allVal && $(this).is(':checked')){
                if($(checkbox + ':checked').length >= ($(checkbox).length - 1)){
                    $(checkbox).prop("checked", 'checked');
                }
                // 若其他取消选中,判断全渠道是否选中, 若是, 将全渠道取消勾选
            }else if($(this).val() != allVal && !$(this).is(':checked')){
                $(checkbox + "[value='" + allVal + "']").prop("checked", '');
            }
        });
    }

     返回随机颜色

    /*
        返回一个随机的颜色字符串
    */
    function getRandomColor(){
        return '#' + Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0');
    }

    计算现在到未来的指定时间还有多少剩余时间

    /*
        返回到指定日期还剩多少天,数字
        参数:
            Y: 年(默认0)
            M: 月(默认0)
            D: 日(默认0)
            h: 时(默认0)
            m: 分(默认0)
            s: 秒(默认0)
    */
    function getCountDown(Y, M, D, h, m, s){
        Y = Y || 0;
        M = M || 0;
        D = D || 0;
        h = h || 0;
        m = m || 0;
        s = s || 0;
        var date = new Date(Y, M-1, D, h, m, s),
        //转换为时间戳,方便计算差值
        times = date.getTime() - new Date().getTime();
        //返回天数
        return Math.ceil(times / (1000 * 60 * 60 * 24));
    }
  • 相关阅读:
    springboot注解@NotNull,@NotBlank,@Valid自动判定空值
    idea打包java可执行jar包
    Spring Boot 默认支持的并发量
    SpringBoot+MyBatis+MySQL读写分离
    Spring+MyBatis实现数据库读写分离方案
    分布式数据库中间件、产品——sharding-jdbc、mycat、drds
    数据库分库分表、读写分离的原理实现,使用场景
    Mono 3.2.3 Socket功能迎来一稳定的版本
    .NET代码树执行时间计时器
    .net好好地利用Conditional属性
  • 原文地址:https://www.cnblogs.com/hujingnb/p/10632954.html
Copyright © 2011-2022 走看看