javascript常用tool.js

//跨浏览器添加事件
/*
function addEvent(obj, type, fn){
    if(typeof obj.addEventListener != ‘undefined‘){
        obj.addEventListener(type, fn, false);
    }else if(typeof obj.attachEvent != ‘undefined‘){
        obj.attachEvent(‘on‘ + type, function(){
            fn.call(obj,window.event);
        });
    }
}
*/
//浏览器监测
(function(){
    window.sys = {};                                     //外部访问浏览器信息对象;
    var ua = navigator.userAgent.toLowerCase();            //浏览器信息字符串
    var s;                                                //浏览器名称加版本

    (s = ua.match(/msie ([\d.]+)/)) ? sys.ie = s[1] :
    (s = ua.match(/firefox\/([\d.]+)/)) ? sys.firefox = s[1] :
    (s = ua.match(/chrome\/([\d.]+)/)) ? sys.chrome = s[1] :
    (s = ua.match(/opera\/.*version\/([\d.]+)/)) ? sys.opera = s[1] :
    (s = ua.match(/version\/([\d.]+).*safari/)) ? sys.safari = s[1] : 0 ;

    if(/webkit/.test(ua)) sys.webkit = ua.match(/webkit\/([\d.]+)/)[1];
    //alert(sys.webkit);
})();

//dom加载
function addDomLoaded(fn){
    var isReady = false;
    var timer = null;
    function doReady(){
        if(timer){
            clearInterval(timer);
        }
        if(isReady){
            return;
        }
        isReady = true;
        fn();
    }

    if((sys.opera && sys.opera < 9) || (sys.firefox < 3) || (sys.webkit && sys.webkit < 525)){
        timer = setInterval(function(){
            if(document && document.getElementById && document.getElementsByTagName && document.body){
                doReady();
            }
        },1);
    }else if(document.addEventListener){
        addEvent(document, ‘DOMContentLoaded‘, function(){
            fn();
            removeEvent(document, ‘DOMContentLoaded‘, arguments.callee);
        });
    }else if(sys.ie && sys.ie < 9){
        var timer = null;
        timer = setInterval(function(){
            try{
                document.documentElement.doScroll(‘left‘);
                doReady();
            }catch(e){};
        },1);
    }
}

function addEvent(obj, type, fn){
    if(typeof obj.addEventListener != ‘undefined‘){
        obj.addEventListener(type, fn, false);
    }else{
        if(!obj.events)obj.events = {};
        if(!obj.events[type]){
            obj.events[type]=[];
            if(obj[‘on‘ + type]) obj.events[type][0] = fn;
        }else{
            if(addEvent.equal(obj.events[type], fn)) return false;
        }
        obj.events[type][addEvent.ID++] = fn;
        obj[‘on‘ + type] = addEvent.exec;
    }
}

addEvent.ID = 1;

addEvent.exec = function (event) {
    var e = event || addEvent.fixEvent(window.event);
    var es = this.events[e.type];
    for(var i in es){
        es[i].call(this, e);
    };
}

addEvent.equal = function(es, fn){
    for(var i in es){
        if(es[i] == fn)return true
    }
    return false;

}

addEvent.fixEvent = function(event){
    event.preventDefault = addEvent.fixEvent.preventDefault;
    event.stopPropagation = addEvent.fixEvent.stopPropagation;
    event.target = event.srcElement;
    return event;
}

addEvent.fixEvent.preventDefault = function(){
    this.returnValue = false;
}

addEvent.fixEvent.stopPropagation = function(){
    this.cancelBubble = true;
}

//跨浏览器删除事件
/*
function removeEvent(obj, type, fn){
    if(typeof obj.removeEventListener != ‘undefined‘){
        obj.removeEventListener(type, fn, false);
    }else if(typeof obj.detachEvent != ‘undefined‘){
        obj.detachEvent(‘on‘+type, fn);
    }
}
*/
function removeEvent(obj, type, fn){
    if(typeof obj.removeEventListener != ‘undefined‘){
        obj.removeEventListener(type, fn, false);
    }else{
        if(obj.events){
            for(var i in obj.events[type]){
                if(obj.events[type][i] == fn){
                    delete obj.events[type][i];
                }
            }
        }
    }
}

//跨浏览器获取视口大小
function getInner(){
    if(typeof window.innerWidth != ‘undefined‘){
        return {
            width:window.innerWidth,
            height:window.innerHeight
        }
    }else{
        return {
            width:document.documentElement.clientWidth,
            height:document.documentElement.clientHeight
        }
    }
}

function getScroll(){
    return {
        top:document.documentElement.scrollTop || document.body.scrollTop,
        left:document.documentElement.scrollLeft || document.body.scrollLeft
    }
}

//获取STYLE
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;
}

//判断class是否存在
function hasClass(element, className){
    return element.className.match(new RegExp(‘(\\s|^)‘+className+‘(\\s|$)‘))
}

//添加LINK规则
function insertRule(sheet, selectorText,cssText, postion){
    if(typeof sheet.insertRule != ‘undefined‘){
        sheet.insertRule(selectorText + ‘{‘ + cssText + ‘}‘, 0);
    }else if(typeof sheet.addRule != ‘undefined‘){
        sheet.addRule(selectorText,cssText, postion);
    }
}

function deleteRule(sheet, index){
    if(typeof sheet.deleteRule != ‘undefined‘){
        sheet.deleteRule(index);
    }else if(typeof sheet.removeRule !=‘undefined‘){
        sheet.removeRule(index);
    }
}

function getInnerText(element){
    return (typeof element.textContent == ‘string‘) ? element.textContent : element.innerText;
}

function setInnerText(element, text){
    if(typeof element.textContent == ‘string‘){
        element.textContent = text;
    }else{
        element.innerText = text;
    }
}

function offsetTop(element){
    var top = element.offsetTop;
    var parent = element.offsetParent;
    while(parent != null){
        top += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return top;
}

//删除左右空格
function trim(str){
    return str.replace(/(^\s*)|(\s*$)/g, ‘‘);
}

function inArray(array, value){
    for(var i in array){
        if(array[i] === value){
            return true;
        }
    }
    return false;
}

function predef(e){
    e.preventDefault();
}

function prevIndex(current, parent){
    var length = parent.children.length;
    if(current == 0) return length-1;
    return parseInt(current) - 1;
}

function nextIndex(current, parent){
    var length = parent.children.length;
    if(current == length - 1) return 0;
    return parseInt(current) + 1;
}

function fixedScroll(){
//setTimeout(function(){
    window.scrollTo(fixedScroll.left, fixedScroll.top);
//},100);
}
/*
function scrollTop(){
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
}*/

//阻止默认行为
function predef(e) {
    e.preventDefault();
}

//创建cookie
function setCookie(name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value);
    if (expires instanceof Date) {
        cookieText += ‘; expires=‘ + expires;
    }
    if (path) {
        cookieText += ‘; expires=‘ + expires;
    }
    if (domain) {
        cookieText += ‘; domain=‘ + domain;
    }
    if (secure) {
        cookieText += ‘; secure‘;
    }
    document.cookie = cookieText;
}

//获取cookie
function getCookie(name) {
    var cookieName = encodeURIComponent(name) + ‘=‘;
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = null;
    if (cookieStart > -1) {
        var cookieEnd = document.cookie.indexOf(‘;‘, cookieStart);
        if (cookieEnd == -1) {
            cookieEnd = document.cookie.length;
        }
        cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    return cookieValue;
}

//删除cookie
function unsetCookie(name) {
    document.cookie = name + "= ; expires=" + new Date(0);
}
时间: 2024-10-23 18:10:17

javascript常用tool.js的相关文章

css常用tool.js

//开启和关闭样式表 function disableStylesheet(ss){ if(typeof ss == 'number'){ document.styleSheets[ss].disabled = true; }else{ var sheets = document.querySelectorAll(ss); for(var i=0; i<sheets.length; i++){ sheets[i].disabled = true; } } }

Tool.js(javascript帮助类)

//string.format $.format = function (source, params) { if (arguments.length == 1) return function () { var args = $.makeArray(arguments); args.unshift(source); return $.validator.format.apply(this, args); }; if (arguments.length > 2 && params.c

Javascript开发技巧(JS入门、运算符、分支结构、循环结构)

一.Js简介和入门 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JavaScript简介</title> <!-- [使用JS的三种方式] 1.HTML标签中内嵌JS(不提倡使用): <button onclick="javascript:alert('小碧池!你真点啊!')">有本事点我呀!!!<

JS表单验证-12个常用的JS表单验证

最近有个项目用到了表单验证,小编在项目完结后的这段时间把常用的JS表单验证demo整理了一下,和大家一起分享~~~ 1. 长度限制 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> 6

JavaScript 常用功能总结

编吐血整理加上翻译,太辛苦了~求赞! 本文主要总结了JavaScript 常用功能总结,如一些常用的额JS 对象,基本数据结构,功能函数等,还有一些常用的设计模式. 目录: 众所周知,JavaScript是动态的面向对象的编程语言,能够实现以下效果: 1. 丰富Web 网页功能 2. 丰富Web界面 3. 实现本地或远程存储. 4. 实现分布式网络应用的前端组件,并在后台进行数据存储管理. 5. 使用JavaScript可以实现完整的分布式Web 应用. JavaScript 中的数据类型 Ja

c#中常用的js语句

1.document.write(""); 输出语句 2.JS中的注释为// 3.传统的HTML文档顺序是:document->html->(head,body) 4.一个浏览器窗口中的DOM顺序是:window->(navigator,screen,history,location,document) 5.得到表单中元素的名称和值:document.getElementById("表单中元素的ID號").name(或value) 6.一个小写转大

javascript 常用函数(二)

/***javascript 常用函数**/function each( object, callback ) { if ( undefined === object.length ){ for ( var name in object ) { if (false === callback( object[name], name, object )) break; } } else { for ( var i = 0, len = object.length; i < len; i++ ) {

封装常用的js(Base.js)——【01】理解库,获取节点,连缀,

封装常用的js(Base.js)——[01]理解库,获取节点,连缀,  youjobit07 2014-10-10 15:32:59 前言:       现如今有太多优秀的开源javascript库,比如jQuery,Prototype,Dojo等等,这些javascript库已经把最常用的代码进行了有效的封装,以便我们开发,从而提高效率.现在我这里探讨的是自己创建一个javascript库,自己创建的肯定没有那些开源javascript库功能强大,目的主要是为了提升自己的原生javascrip

javascript常用排序算法实现

毕业后,由于工作中很少需要自已去写一些排序,所以那些排序算法都忘得差不多了,不过排序是最基础的算法,还是不能落下啦,于是找了一些资料,然后用Javascript实现了一些常用的算法,具体代码如下: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>