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参数   {width: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));
}

猜你喜欢

转载自www.cnblogs.com/hujingnb/p/10632954.html