澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

js常用函数二〇一〇,分享前端开辟常用代码片段

2019-11-10 作者:澳门新萄京赌场网址   |   浏览(184)

分享前端开垦常用代码片段

2018/05/05 · JavaScript · 1 评论 · 代码

原稿出处: WEBING   

时常应用的 JS 方法,今日记下,以便现在查询

//js常用函数 更新二〇〇九-8-16 取自网络

大器晚成、预加载图像

假定您的网页中需求动用大量开头不可以知道的(比方,悬停的卡塔 尔(阿拉伯语:قطر‎图像,那么能够预加载这么些图像。澳门新萄京官方网站 1

/* 手提式有线电话机类型判定 */

澳门新萄京官方网站 2

function $(id) {
return document.getElementById(id);
}

二、检查图疑似否加载

一时为了世襲脚本,你大概须要检查图疑似否全体加载完结。澳门新萄京官方网站 3

您也足以选择 ID 或 CLASS 替换<img> 标签来检查某个特定的图疑似否被加载。

复制代码 代码如下:

时有时应用的 JS 方法,前日记录,以便以往查询。

/**************
函数:getElementsByClassName
使用格局:
获取document内的超链接class是“info-links”的。
getElementsByClassName(document, "a", "info-links");
获取container内的div的class是col的.
getElementsByClassName(document.getElementById("container"), "div", "col");
获得document内的保有class是“click-me”的。
getElementsByClassName(document, "*", "click-me");
回来二个数组
**************/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "-");
var oRegExp = new RegExp("(^|s)" strClassName "(s|$)");
var oElement;
for(var i=0; i<arrElements.length; i ){
oElement = arrElements[i];
if(oRegExp.test(oElement.className))
arrReturnElements.push(oElement);
}
return (arrReturnElements)
}

三、自动修复破坏的图像

逐大器晚成替换已经损坏的图像链接是非常痛楚的。但是,上边这段轻易的代码能够扶植您。澳门新萄京官方网站 4

var BrowserInfo = {
    userAgent: navigator.userAgent.toLowerCase()
    isAndroid: Boolean(navigator.userAgent.match(/android/ig)),
    isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),
    isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),
    isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),
}

/* 手提式有线电电话机类型判定 */

/**************
replaceAll:
更迭字符串中的字符。
用法:
yourstring.replaceAll("要替换的字符", "替换来什么");
例子:
"cssrain".replaceAll("s", "a");
" cs sr ai n".replaceAll(" ", "");
**************/
String.prototype.replaceAll = function (AFindText,ARepText){
raRegExp = new RegExp(AFindText,"g");
return this.replace(raRegExp,ARepText);
}

四、悬停切换

当客户鼠标悬停在可点击的因素上时,可增加类到成分中,反之则移除类。澳门新萄京官方网站 5

只需求丰富要求的 CSS 就能够。更简明的方法是应用 toggleClass() 方法。澳门新萄京官方网站 6

/* 再次来到字符串长度,男人计数为2  */


var BrowserInfo = {
userAgent: navigator.userAgent.toLowerCase()
isAndroid: Boolean(navigator.userAgent.match(/android/ig)),
isIphone: Boolean(navigator.userAgent.match(/iphone|ipod/ig)),
isIpad: Boolean(navigator.userAgent.match(/ipad/ig)),
isWeixin: Boolean(navigator.userAgent.match(/MicroMessenger/ig)),
}

 

/**************
* 字符串前后空格管理。
* 假设想替换中间的空格,请用replaceAll方法。
* 用法:
* " cssrain ".trim();
**************/
String.prototype.trim=function()
{
return this.replace(/(^s*)|(s*$)/g,"");//将字符串前后空格,用空字符串代替。
}

五、淡入淡出/突显隐敝

复制代码 代码如下:

/* 重回字符串长度,男生计数为2 */

/**************
* 总结字符串的实在长度
//String有天个性length,但是它不可能分别希伯来语字符,
//计算普通话字符和全角字符。可是在数据存款和储蓄的时候汉语和全角都以用三个字节来存款和储蓄的,
//全部要求额外管理一下。自个儿写了个函数,重返String正真的长度.
用法:
<input type="text" name="rain" id="rain" />
<input type="button" id="test" value="test" onclick="alert( document.getElementById('rain').value.codeLength() )"/>
**************/
String.prototype.codeLength=function(){
var len=0;
if(this==null||this.length==0)
return 0;
var str=this.replace(/(^s*)|(s*$)/g,"");//去掉空格
for(i=0;i<str.length;i )
if(str.charCodeAt(i)>0&&str.charCodeAt(i)<128)
len ;
else
len =2;
return len;
}

澳门新萄京官方网站 7

function strLength(str) {
    var a = 0;
    for (var i = 0; i < str.length; i ) {
        if (str.charCodeAt(i) > 255)
            a = 2;//依据预期计数扩大2
        else
            a ;
    }
    return a;
}


function strLength(str) {
var a = 0;
for (var i = 0; i < str.length; i ) {
if (str.charCodeAt(i) > 255)
a = 2;//依据预期计数增添2
else
a ;
}
return a;
}

//JS获取字符串的莫过于尺寸,用来代表 String的length属性
String.prototype.length = function(){
return this.replace(/[u4e00-u9fa5] /g,"**").length;
}

六、鼠标滚轮

$('#content').on("mousewheel DOMMouseScroll", function (event) { // chrome & ie || // firefox var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) || (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1)); if (delta > 0) { console.log('mousewheel top'); } else if (delta < 0) { console.log('mousewheel bottom'); } });

1
2
3
4
5
6
7
8
9
10
11
$('#content').on("mousewheel DOMMouseScroll", function (event) {
    // chrome & ie || // firefox
    var delta = (event.originalEvent.wheelDelta && (event.originalEvent.wheelDelta > 0 ? 1 : -1)) ||
        (event.originalEvent.detail && (event.originalEvent.detail > 0 ? -1 : 1));  
    
    if (delta > 0) {
        console.log('mousewheel top');
    } else if (delta < 0) {
        console.log('mousewheel bottom');
    }
});

赢得url中的参数

收获url中的参数

/**************
//过滤HTML
//在商讨的时候为了防守用户提交带有恶意的脚本,能够先过滤HTML标签,过滤掉双引号,单引号,符号&,符号<,符号
用法:
<input type="text" name="rain" id="rain" />
<input type="button" id="test" value="test" onclick="alert( document.getElementById('rain').value.filterHtml() )"/>
**************/
String.prototype.filterHtml=function(){
return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");
}

七、鼠标坐标

复制代码 代码如下:


function GetQueryStringRegExp(name,url) {
var reg = new RegExp("(^|?|&)" name "=([^&]*)(s|&|$)", "i");
if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/ /g, " ")); return "";
}

/**************
format:
格式化时间。
用法:
yourdate.format("你的日子格式");
例子:
obj0 = new Date("Sun May 04 2008").format("yyyy-MM-dd");
obj1 = new Date().format("yyyy-MM-dd hh:mm:ss");
obj2 = new Date().format("yyyy-MM-dd");
obj3 = new Date().format("yyyy/MM/dd");
obj4 = new Date().format("MM/dd/yyyy");
**************/
Date.prototype.format = function(format)
{
var o = {
"M " : this.getMonth() 1, //month
"d " : this.getDate(), //day
"h " : this.getHours(), //hour
"m " : this.getMinutes(), //minute
"s " : this.getSeconds(), //second
"q " : Math.floor((this.getMonth() 3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y )/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear() "").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("(" k ")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00" o[k]).substr(("" o[k]).length));
return format;
}

1、JavaScript实现

X:<input id="xxx" type="text" /> Y:<input id="yyy" type="text" />

1
X:<input id="xxx" type="text" /> Y:<input id="yyy" type="text" />

function mousePosition(ev){ if(ev.pageX || ev.pageY){ return {x:ev.pageX, y:ev.pageY}; } return { x:ev.clientX document.body.scrollLeft - document.body.clientLeft, y:ev.clientY document.body.scrollTop - document.body.clientTop }; } function mouseMove(ev){ ev = ev || window.event; var mousePos = mousePosition(ev); document.getElementById('xxx').value = mousePos.x; document.getElementById('yyy').value = mousePos.y; } document.onmousemove = mouseMove;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function mousePosition(ev){
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }
    return {
        x:ev.clientX document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY document.body.scrollTop - document.body.clientTop
    };
}
 
function mouseMove(ev){
    ev = ev || window.event;
    
    var mousePos = mousePosition(ev);
    
    document.getElementById('xxx').value = mousePos.x;
    document.getElementById('yyy').value = mousePos.y;
}
document.onmousemove = mouseMove;

function GetQueryStringRegExp(name,url) {
    var reg = new RegExp("(^|\?|&)" name "=([^&]*)(\s|&|$)", "i");
    if (reg.test(url)) return decodeURIComponent(RegExp.$2.replace(/ /g, " ")); return "";
}

/* js 绑定事件 适用于别的浏览器的要素绑定 */

/**************
format:
格式化数字.
例子:
var n = format_number( 123456.45656 , 2 ); // .toFixed(2)也能够兑现,不过不宽容FF.
alert(n);
**************/
function format_number(str,digit)
{
if(isNaN(str))
{
alert("您传入的值不是数字!");
return 0;
}
else if(Math.round(digit)!=digit)
{
alert("您输入的小数位数不是整数!");
return 0;
}
else
return Math.round(parseFloat(str)*Math.pow(10,digit))/Math.pow(10,digit);
}

2、jQuery实现

$('#ele').click(function(event){ //获取鼠标在图纸上的坐标 console.log('X:' event.offsetX 'n Y:' event.offsetY); //获取成分相对于页面包车型大巴坐标 console.log('X:' $(this).offset().left 'n Y:' $(this).offset().top); });

1
2
3
4
5
6
7
$('#ele').click(function(event){
    //获取鼠标在图片上的坐标
    console.log('X:' event.offsetX 'n Y:' event.offsetY);
    
    //获取元素相对于页面的坐标
    console.log('X:' $(this).offset().left 'n Y:' $(this).offset().top);
});

  


function eventBind(obj, eventType, callBack) {
if (obj.addEventListener) {
obj.addEventListener(eventType, callBack, false);
}
else if (window.attachEvent) {
obj.attachEvent('on' eventType, callBack);
}
else {
obj['on' eventType] = callBack;
}
};
eventBind(document, 'click', bodyClick);

/**********表单操作*********/

八、制止移动端浏览器页面滚动

/* js 绑定事件 适用于其余浏览器的要素绑定  */

/* 得到当前浏览器JS的版本 */

/**************
* 获得单选框选中的值。
* 用法:
*<input type="radio" value="1" name="cssrain"/>
*<input type="radio" value="2" name="cssrain" checked/>
*<input type="radio" value="3" name="cssrain"/>
*<input type="button" onclick="alert(getRadioValue('cssrain'))" value="test"/>
**************/
function getRadioValue(radioName){
var obj=document.getElementsByName(radioName);
for(var i=0;i<obj.length;i ){
if(obj[i].checked){
return obj[i].value;
}
}
}

1、HTML实现

<body ontouchmove="event.preventDefault()" >

1
<body ontouchmove="event.preventDefault()" >

复制代码 代码如下:


function getjsversion(){
var n = navigator;
var u = n.userAgent;
var apn = n.appName;
var v = n.appVersion;
var ie = v.indexOf('MSIE ');
if (ie > 0){
apv = parseInt(i = v.substring(ie 5));
if (apv > 3) {
apv = parseFloat(i);
}
} else {
apv = parseFloat(v);
}
var isie = (apn == 'Microsoft Internet Explorer');
var ismac = (u.indexOf('Mac') >= 0);
var javascriptVersion = "1.0";
if (String && String.prototype) {
javascriptVersion = '1.1';
if (javascriptVersion.match) {
javascriptVersion = '1.2';
var tm = new Date;
if (tm.setUTCDate) {
javascriptVersion = '1.3';
if (isie && ismac && apv >= 5) javascriptVersion = '1.4';
var pn = 0;
if (pn.toPrecision) {
javascriptVersion = '1.5';
a = new Array;
if (a.forEach) {
javascriptVersion = '1.6';
i = 0;
o = new Object;
tcf = new Function('o', 'var e,i=0;try{i=new Iterator(o)}catch(e){}return i');
i = tcf(o);
if (i && i.next) {
javascriptVersion = '1.7';
}
}
}
}
}
}
return javascriptVersion;
}

/**************
* 复选框全选/不选/反选
* 用法:
<form id="form_a">
<input type="checkbox" value="1" name="a"/>
<input type="checkbox" value="2" name="a" checked/>
<input type="checkbox" value="3" name="a"/>
<input type="button" value="全选" onclick="checkAll(document.getElementById('form_a'),'all')"/>
<input type="button" value="不选" onclick="checkAll(document.getElementById('form_a'),'none')"/>
<input type="button" value="反选" onclick="checkAll(document.getElementById('form_a'),'')"/>
</form>
**************/
function checkAll(form, sel) {
for (i = 0, n = form.elements.length; i < n; i ) {
if(form.elements[i].type == "checkbox") {
if(form.elements[i].checked == true) {
form.elements[i].checked = (sel == "all" ? true : false);
} else {
form.elements[i].checked = (sel == "none" ? false : true);
}
}
}
}

2、JavaScript实现

document.addEventListener('touchmove', function(event) { event.preventDefault(); });

1
2
3
document.addEventListener('touchmove', function(event) {
    event.preventDefault();
});

function eventBind(obj, eventType, callBack) {
        if (obj.addEventListener) {
            obj.addEventListener(eventType, callBack, false);
        }
        else if (window.attachEvent) {
            obj.attachEvent('on' eventType, callBack);
        }
        else {
            obj['on' eventType] = callBack;
        }
    };
eventBind(document, 'click', bodyClick);

/* 获取当前点击事件的Object对象 */

/**************
* 复选框检查是不是选中。
* 要是没叁在那之中选,会再次回到false.
* 用法:
<form id="form_a" name="form_a">
<input type="checkbox" value="1" name="a"/>
<input type="checkbox" value="2" name="a" checked/>
<input type="checkbox" value="3" name="a"/>
<input type="button" value="全选" onclick="alert( SCheckBox('form_a','a') )"/>
</form>
**************/
function SCheckBox(_formName,_checkboxName){
var selflag = {'checked':0,'cvalues':[]};
_scheckbox = eval('document.' _formName '.' _checkboxName);
if(_scheckbox){
if(eval(_scheckbox.length)){
for(i=0;i<_scheckbox.length;i ){
if(_scheckbox[i].checked){
selflag.checked ;
selflag.cvalues.push(_scheckbox[i].value);
}
};
}else if(_scheckbox.checked){
selflag.checked ;
selflag.cvalues.push(_scheckbox.value);
}
if(selflag.checked){
return selflag;
}
}
return false;
}

九、阻止暗许行为

// JavaScript document.getElementById('btn').addEventListener('click', function (event) { event = event || window.event; if (event.preventDefault){ // W3C event.preventDefault(); } else{ // IE event.returnValue = false; } }, false); // jQuery $('#btn').on('click', function (event) { event.preventDefault(); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// JavaScript
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;
 
    if (event.preventDefault){
        // W3C
        event.preventDefault();
    } else{
        // IE
        event.returnValue = false;
    }
}, false);
 
// jQuery
$('#btn').on('click', function (event) {
    event.preventDefault();
});

  


function getEvent() {
if (document.all) {
return window.event; //如果是ie
}
func = getEvent.caller;
while (func != null) {
var arg0 = func.arguments[0];
if (arg0) {
if ((arg0.constructor == Event || arg0.constructor == MouseEvent)
|| (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
return arg0;
}
}
func = func.caller;
}
return null;
};

//就算控件值=原本值则清空
function clearInput(input){
if(input.value == input.defaultValue){
input.value = "";
}
}

十、阻止冒泡

// JavaScript document.getElementById('btn').addEventListener('click', function (event) { event = event || window.event; if (event.stopPropagation){ // W3C event.stopPropagation(); } else{ // IE event.cancelBubble = true; } }, false); // jQuery $('#btn').on('click', function (event) { event.stopPropagation(); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// JavaScript
document.getElementById('btn').addEventListener('click', function (event) {
    event = event || window.event;
 
    if (event.stopPropagation){
        // W3C
        event.stopPropagation();
    } else{
        // IE
        event.cancelBubble = true;
    }
}, false);
 
// jQuery
$('#btn').on('click', function (event) {
    event.stopPropagation();
});

/* 取妥当前浏览器JS的版本 */

/* 字符串截取方法 */

/***************表单操作结束**********/

十后生可畏、检查评定浏览器是还是不是协理svg

function isSupportSVG() { var SVG_NS = ''; return !!document.createElementNS &&!!document.createElementNS(SVG_NS, 'svg').createSVGRect; } console.log(isSupportSVG());

1
2
3
4
5
6
function isSupportSVG() {
    var SVG_NS = 'http://www.w3.org/2000/svg';
    return !!document.createElementNS &&!!document.createElementNS(SVG_NS, 'svg').createSVGRect;
}
 
console.log(isSupportSVG());

复制代码 代码如下:


getCharactersLen: function (charStr, cutCount) {
if (charStr == null || charStr == '') return '';
var totalCount = 0;
var newStr = '';
for (var i = 0; i < charStr.length; i ) {
var c = charStr.charCodeAt(i);
if (c < 255 && c > 0) {
totalCount ;
} else {
totalCount = 2;
}
if (totalCount >= cutCount) {
newStr = charStr.charAt(i);
break;
}
else {
newStr = charStr.charAt(i);
}
}
return newStr;
}

/**************/
//收藏到书签.(宽容IE和FF)。

十九、检测浏览器是还是不是帮忙canvas

function isSupportCanvas() { if(document.createElement('canvas').getContext){ return true; }else{ return false; } } console.log(isSupportCanvas());

1
2
3
4
5
6
7
8
9
function isSupportCanvas() {
    if(document.createElement('canvas').getContext){
        return true;
    }else{
        return false;
    }
}
 
console.log(isSupportCanvas());

function getjsversion(){
    var n = navigator;
    var u = n.userAgent;
    var apn = n.appName;
    var v = n.appVersion;
    var ie = v.indexOf('MSIE ');
    if (ie > 0){
        apv = parseInt(i = v.substring(ie 5));
        if (apv > 3) {
            apv = parseFloat(i);
        }
    } else {
        apv = parseFloat(v);
    }
    var isie = (apn == 'Microsoft Internet Explorer');
    var ismac = (u.indexOf('Mac') >= 0);
    var javascriptVersion = "1.0";
    if (String && String.prototype) {
        javascriptVersion = '1.1';
        if (javascriptVersion.match) {
            javascriptVersion = '1.2';
            var tm = new Date;
            if (tm.setUTCDate) {
                javascriptVersion = '1.3';
                if (isie && ismac && apv >= 5) javascriptVersion = '1.4';
                var pn = 0;
                if (pn.toPrecision) {
                    javascriptVersion = '1.5';
                    a = new Array;
                    if (a.forEach) {
                        javascriptVersion = '1.6';
                        i = 0;
                        o = new Object;
                        tcf = new Function('o', 'var e,i=0;try{i=new Iterator(o)}catch(e){}return i');
                        i = tcf(o);
                        if (i && i.next) {
                            javascriptVersion = '1.7';
                        }
                    }
                }
            }
        }
    }
    return javascriptVersion;
}

/* JS 弹出新窗口全屏 */

function addBookmark(title,url) {
if (window.sidebar) {
window.sidebar.addPanel(title, url,"");
} else if( document.all ) {
window.external.AddFavorite( url, title);
} else if( window.opera && window.print ) {
return true;
}
}

十二、检测是或不是是Wechat浏览器

function isWeiXinClient() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i)=="micromessenger") { return true; } else { return false; } } alert(isWeiXinClient());

1
2
3
4
5
6
7
8
9
10
function isWeiXinClient() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}
 
alert(isWeiXinClient());

/* 获取当前点击事件的Object对象 */


var tmp = window.open("about:blank", "", "fullscreen=1")
tmp.moveTo(0, 0);
tmp.resizeTo(screen.width 20, screen.height);
tmp.focus();
tmp.location.href = '//www.che168.com/pinggu/eva' msgResult.message[0] '.html';
var config
= "left=0,top=0,width=" (window.screen.Width) ",height=" (window.screen.Height);
window.open('//www.che168.com/pinggu/eva' msgResult.message[0] '.html', "winHanle", config);
//模拟form提交张开新页面
var f = document.createElement("form");
f.setAttribute('action', '//www.che168.com/pinggu/eva_' msgResult.message[0] '.html');
f.target = '_blank';
document.body.appendChild(f);
f.submit();

/**************
函数 : 文本框得到与失去宗旨 操作。
那一个方法平时在文本框寻找的时候现身。
文本里展现 “ 寻觅 ”,然后当客户鼠标点击此文件,
文本框内容清空。要是客商没填写内容,那么文本的值又大张旗鼓。
万意气风发填写了,就显示客户填写的。
用法:
<input type="" value="关键字搜索" name="a" onfocus="clearTxt('a','关键字寻找')" onblur="fillTxt('a','关键字寻找')"/>
<input type="text" value="test" name="test" />
**************/
function clearTxt(id,txt) {
if (document.getElementById(id).value == txt)
document.getElementById(id).value="" ;
return ;
}
function fillTxt(id,txt) {
if ( document.getElementById(id).value == "" )
document.getElementById(id).value=txt;
return ;
}

十一、检查测验是不是移动端及浏览器内核

var browser = { versions: function() { var u = navigator.userAgent; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌(Google卡塔尔水源 gecko: u.indexOf('Firefox') > -1, //火狐内核Gecko mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是或不是移动终端 ios: !!u.match(/(i[^;] ;( U;)? CPU. Mac OS X/), //ios android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android iPhone: u.indexOf('iPhone') > -1 , //iPhone iPad: u.indexOf('iPad') > -1, //iPad webApp: u.indexOf('Safari') > -1 //Safari }; } } if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad()) { alert('移动端'); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var browser = {
    versions: function() {
        var u = navigator.userAgent;
        return {
            trident: u.indexOf('Trident') > -1, //IE内核
            presto: u.indexOf('Presto') > -1, //opera内核
            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
            gecko: u.indexOf('Firefox') > -1, //火狐内核Gecko
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否移动终端
            ios: !!u.match(/(i[^;] ;( U;)? CPU. Mac OS X/), //ios
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android
            iPhone: u.indexOf('iPhone') > -1 , //iPhone
            iPad: u.indexOf('iPad') > -1, //iPad
            webApp: u.indexOf('Safari') > -1 //Safari
        };
    }
}
 
if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad()) {
    alert('移动端');
}

复制代码 代码如下:

/* 全选/全不选 */

/**************
函数 : 用来判断鼠标按的是左键照旧右键。(宽容IE和ff)
用法:
onmousedown="mouse_keycode(event)"
**************/
function mouse_keycode(event){
var event=event||window.event;
var nav=window.navigator.userAgent;
if (nav.indexOf("MSIE")>=1) //假设浏览器为IE.解释:因为 document.all 是 IE 的蓄意属性,所以平日用这些点子来判别客商端是不是是IE浏览器 ,document.all?1:0;
{
if(event.button==1){alert("左键")}
else if(event.button==2){alert("右键")}
}
else if(nav.indexOf("Firefox")>=1) ////假若浏览器为Firefox
{
if(event.button==0){alert("左键");}
else if(event.button==2){alert("右键");}
}
else{ //假如浏览器为其余
alert("other");
}
}

十九、检验是还是不是Computer端/移动端

var browser={ versions:function(){ var u = navigator.userAgent, app = navigator.appVersion; var sUserAgent = navigator.userAgent; return { trident: u.indexOf('Trident') > -1, presto: u.indexOf('Presto') > -1, isChrome: u.indexOf("chrome") > -1, isSafari: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u), isSafari3: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u) && u.indexOf('webkit/5') != -1, webKit: u.indexOf('AppleWebKit') > -1, gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, mobile: !!u.match(/AppleWebKit.*Mobile.*/), ios: !!u.match(/(i[^;] ;( U;)? CPU. Mac OS X/), android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, iPhone: u.indexOf('iPhone') > -1, iPad: u.indexOf('iPad') > -1, iWinPhone: u.indexOf('Windows Phone') > -1 }; }() } if(browser.versions.mobile || browser.versions.iWinPhone){ window.location = "http:/www.baidu.com/m/"; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var browser={
    versions:function(){
        var u = navigator.userAgent, app = navigator.appVersion;
        var sUserAgent = navigator.userAgent;
        return {
        trident: u.indexOf('Trident') > -1,
        presto: u.indexOf('Presto') > -1,
        isChrome: u.indexOf("chrome") > -1,
        isSafari: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u),
        isSafari3: !u.indexOf("chrome") > -1 && (/webkit|khtml/).test(u) && u.indexOf('webkit/5') != -1,
        webKit: u.indexOf('AppleWebKit') > -1,
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
        mobile: !!u.match(/AppleWebKit.*Mobile.*/),
        ios: !!u.match(/(i[^;] ;( U;)? CPU. Mac OS X/),
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
        iPhone: u.indexOf('iPhone') > -1,
        iPad: u.indexOf('iPad') > -1,
        iWinPhone: u.indexOf('Windows Phone') > -1
        };
    }()
}
if(browser.versions.mobile || browser.versions.iWinPhone){
    window.location = "http:/www.baidu.com/m/";
}

function getEvent() {
    if (document.all) {
        return window.event; //如果是ie
    }
    func = getEvent.caller;
    while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0) {
            if ((arg0.constructor == Event || arg0.constructor == MouseEvent)
|| (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                return arg0;
            }
        }
        func = func.caller;
    }
    return null;
};


function selectAll(objSelect) {
if (objSelect.checked == true) {
$("input[name='chkId']").attr("checked", true);
$("input[name='chkAll']").attr("checked", true);
}
else if (objSelect.checked == false) {
$("input[name='chkId']").attr("checked", false);
$("input[name='chkAll']").attr("checked", false);
}
}

 

/**************
函数 :触发有些对象的onclick事件。(包容IE和FF卡塔尔国
用法:
<input type="button" value="aaa" id="a" onclick=" alert('cssrain') " />
<input type="button" value="触发ID为a的onclick事件" onclick=" handerToClick('a') " />
**************/
function handerToClick(objid){
var obj=document.getElementById(objid);
if(document.all){
obj.fireEvent("onclick");
}else{
var e=document.createEvent('MouseEvent');
e.initEvent('click',false,false);
obj.dispatchEvent(e);
}
}

十七、检查实验浏览器内核

function getInternet(){ if(navigator.userAgent.indexOf("MSIE")>0) { return "MSIE"; //IE浏览器 } if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){ return "Firefox"; //Firefox浏览器 } if(isSafari=navigator.userAgent.indexOf("Safari")>0) { return "Safari"; //Safan浏览器 } if(isCamino=navigator.userAgent.indexOf("Camino")>0){ return "Camino"; //Camino浏览器 } if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){ return "Gecko"; //Gecko浏览器 } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function getInternet(){    
    if(navigator.userAgent.indexOf("MSIE")>0) {    
      return "MSIE";       //IE浏览器  
    }  
 
    if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){    
      return "Firefox";     //Firefox浏览器  
    }  
 
    if(isSafari=navigator.userAgent.indexOf("Safari")>0) {    
      return "Safari";      //Safan浏览器  
    }  
 
    if(isCamino=navigator.userAgent.indexOf("Camino")>0){    
      return "Camino";   //Camino浏览器  
    }  
    if(isMozilla=navigator.userAgent.indexOf("Gecko/")>0){    
      return "Gecko";    //Gecko浏览器  
    }    
}

  

/* js 决断浏览器 */

/**************
贯彻按回车提交
**************/
function QuickPost(evt,form){
var evt = window.event?window.event:evt;
if(evt.keyCode == 13){
document.getElementById(form).submit();
}
}

十六、强制移动端页面横屏展现

$( window ).on( "orientationchange", function( event ) { if (event.orientation=='portrait') { $('body').css('transform', 'rotate(90deg)'); } else { $('body').css('transform', 'rotate(0deg)'); } }); $( window ).orientationchange();

1
2
3
4
5
6
7
8
$( window ).on( "orientationchange", function( event ) {
    if (event.orientation=='portrait') {
        $('body').css('transform', 'rotate(90deg)');
    } else {
        $('body').css('transform', 'rotate(0deg)');
    }
});
$( window ).orientationchange();

/* 字符串截取方法  */


判定是不是是 IE 浏览器
if (document.all){
alert(”IE浏览器”);
}else{
alert(”非IE浏览器”);
}
if (!!window.ActiveXObject){
alert(”IE浏览器”);
}else{
alert(”非IE浏览器”);
}
判断是IE几
var isIE=澳门新萄京官方网站,!!window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var isIE8=isIE&&!!document.documentMode;
var isIE7=isIE&&!isIE6&&!isIE8;
if (isIE){
if (isIE6){
alert(”ie6″);
}else if (isIE8){
alert(”ie8″);
}else if (isIE7){
alert(”ie7″);
}
}

/*********
表明是不是是数字
**********/
function checkIsInteger(str)
{
//若是为空,则经过校验
if(str == "")
return true;
if(/^(-?)(d )$/.test(str))
return true;
else
return false;
}

十四、计算机端页面全屏彰显

function fullscreen(element) { if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } } fullscreen(document.documentElement);

1
2
3
4
5
6
7
8
9
10
11
12
13
function fullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
    }
}
 
fullscreen(document.documentElement);

复制代码 代码如下:

/* 判定浏览器 */

更新2009-8-16 取自互连网 function $(id) { return document.getElementById(id); } /************** 函数:getElementsByClassName 使用办法: 获取document内的...

十四、得到/失去宗旨

getCharactersLen: function (charStr, cutCount) {
        if (charStr == null || charStr == '') return '';
        var totalCount = 0;
        var newStr = '';
        for (var i = 0; i < charStr.length; i ) {
            var c = charStr.charCodeAt(i);
            if (c < 255 && c > 0) {
                totalCount ;
            } else {
                totalCount = 2;
            }
            if (totalCount >= cutCount) {
                newStr = charStr.charAt(i);
                break;
            }
            else {
                newStr = charStr.charAt(i);
            }
        }
        return newStr;
    }


function getOs() {
if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
return "MSIE8";
}
else if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
return "MSIE6";
}
else if (navigator.userAgent.indexOf("MSIE 7.0") > 0) {
return "MSIE7";
}
else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
return "Firefox";
}
if (navigator.userAgent.indexOf("Chrome") > 0) {
return "Chrome";
}
else {
return "Other";
}
}

1、JavaScript实现

<input id="i_input" type="text" value="会员卡号/手提式有线电电话机号"/>

1
<input id="i_input" type="text" value="会员卡号/手机号"/>

// JavaScript window.onload = function(){ var oIpt = document.getElementById("i_input"); if(oIpt.value == "会员卡号/手提式有线电话机号"){ oIpt.style.color = "#888"; }else{ oIpt.style.color = "#000"; }; oIpt.onfocus = function(){ if(this.value == "会员卡号/手提式有线话机号"){ this.value=""; this.style.color = "#000"; this.type = "password"; }else{ this.style.color = "#000"; } }; oIpt.onblur = function(){ if(this.value == ""){ this.value="会员卡号/手提式有线电话机号"; this.style.color = "#888"; this.type = "text"; } }; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// JavaScript
window.onload = function(){
    var oIpt = document.getElementById("i_input");
 
    if(oIpt.value == "会员卡号/手机号"){
        oIpt.style.color = "#888";
    }else{
        oIpt.style.color = "#000";
    };
 
    oIpt.onfocus = function(){
        if(this.value == "会员卡号/手机号"){
            this.value="";
            this.style.color = "#000";
            this.type = "password";
        }else{
            this.style.color = "#000";
        }
    };
    
    oIpt.onblur = function(){
        if(this.value == ""){
            this.value="会员卡号/手机号";
            this.style.color = "#888";
            this.type = "text";
        }
    };
}

  

/* JS决断七个日子大小 相符 二〇一三-09-09 与二〇一一-9-9 三种格式的相比较 */

2、jQuery实现

<input type="text" class="oldpsw" id="showPwd" value="请输入您的挂号密码"/> <input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;"/>

1
2
<input type="text" class="oldpsw" id="showPwd" value="请输入您的注册密码"/>
<input type="password" name="psw" class="oldpsw" id="password" value="" style="display:none;"/>

// jQuery $("#showPwd").focus(function() { var text_value=$(this).val(); if (text_value =='请输入您的注册密码') { $("#showPwd").hide(); $("#password").show().focus(); } }); $("#password").blur(function() { var text_value = $(this).val(); if (text_value == "") { $("#showPwd").show(); $("#password").hide(); } });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// jQuery
$("#showPwd").focus(function() {
    var text_value=$(this).val();
    if (text_value =='请输入您的注册密码') {
        $("#showPwd").hide();
        $("#password").show().focus();
    }
});
$("#password").blur(function() {
    var text_value = $(this).val();
    if (text_value == "") {
        $("#showPwd").show();
        $("#password").hide();
    }
});

/*  JS 弹出新窗口全屏  */


//获得日期值并转形成日期格式,replace(/-/g, "/")是基于表达表达式把日子转产生长日期格式,这样再张开推断就好判定了
function ValidateDate() {
var beginDate = $("#t_datestart").val();
var endDate = $("#t_dateend").val();
if (beginDate.length > 0 && endDate.length>0) {
var sDate = new Date(beginDate.replace(/-/g, "/"));
var eDate= new Date(endDate.replace(/-/g, "/"));
if (sDate > eDate) {
alert('起先日期要破罐破摔结束日期');
return false;
}
}
}

三十、获取上传文件大小

<input type="file" id="filePath" onchange="getFileSize(this)"/>

1
<input type="file" id="filePath" onchange="getFileSize(this)"/>

// 兼容IE9低版本 function getFileSize(obj){ var filesize; if(obj.files){ filesize = obj.files[0].size; }else{ try{ var path,fso; path = document.getElementById('filePath').value; fso = new ActiveXObject("Scripting.FileSystemObject"); filesize = fso.GetFile(path).size; } catch(e){ // 在IE9及低版本浏览器,若是不容许ActiveX控件与页面交互作用,点击了否,就不可能得到size console.log(e.message); // Automation 服务器无法创制对象 filesize = 'error'; // 不可能赢得 } } return filesize; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 兼容IE9低版本
function getFileSize(obj){
    var filesize;
    
    if(obj.files){
        filesize = obj.files[0].size;
    }else{
        try{
            var path,fso;
            path = document.getElementById('filePath').value;
            fso = new ActiveXObject("Scripting.FileSystemObject");
            filesize = fso.GetFile(path).size;
        }
        catch(e){
            // 在IE9及低版本浏览器,如果不容许ActiveX控件与页面交互,点击了否,就无法获取size
            console.log(e.message); // Automation 服务器不能创建对象
            filesize = 'error'; // 无法获取
        }
    }
    return filesize;
}

复制代码 代码如下:

/* 移除事件 */

七十一、节制上传文件类型

var tmp = window.open("about:blank", "", "fullscreen=1")
                            tmp.moveTo(0, 0);
                            tmp.resizeTo(screen.width 20, screen.height);
                            tmp.focus();
                            tmp.location.href = '' msgResult.message[0] '.html';
 
var config_ = "left=0,top=0,width=" (window.screen.Width) ",height=" (window.screen.Height);
                            window.open('' msgResult.message[0] '.html', "winHanle", config_);
//模拟form提交展开新页面
var f = document.createElement("form");
                            f.setAttribute('action', '' msgResult.message[0] '.html');
                            f.target = '_blank';
                            document.body.appendChild(f);
                            f.submit();


this.moveBind = function (objId, eventType, callBack) {
var obj = document.getElementById(objId);
if (obj.removeEventListener) {
obj.removeEventListener(eventType, callBack, false);
}
else if (window.detachEvent) {
obj.detachEvent('on' eventType, callBack);
}
else {
obj['on' eventType] = null;
}
}

1、高版本浏览器

<input type="file" name="filePath" accept=".jpg,.jpeg,.doc,.docxs,.pdf"/>

1
<input type="file" name="filePath" accept=".jpg,.jpeg,.doc,.docxs,.pdf"/>

/*   全选/全不选  */

/* 回车提交 */

2、约束图片

<input type="file" class="file" value="上传" accept="image/*">

1
<input type="file" class="file" value="上传" accept="image/*">

复制代码 代码如下:


$("id").onkeypress = function (event) {
event = (event) ? event : ((window.event) ? window.event : "")
keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode);
if (keyCode == 13) {
$("SubmitLogin").onclick();
}
}

3、低版本浏览器

<input type="file" id="filePath" onchange="limitTypes()">

1
<input type="file" id="filePath" onchange="limitTypes()">

/* 通过扩展名,核实文件格式。 * @parma file帕特h{string} 文件路线 * @parma acceptFormat{Array} 允许的文件类型 *js常用函数二〇一〇,分享前端开辟常用代码片段。 <a href="; 返回值{Boolen}:true or false */ function checkFormat(filePath,acceptFormat){ var resultBool= false, ex = filePath.substring(filePath.lastIndexOf('.') 1); ex = ex.toLowerCase(); for(var i = 0; i < acceptFormat.length; i ){   if(acceptFormat[i] == ex){ resultBool = true; break;   } } return resultBool; }; function limitTypes(){ var obj = document.getElementById('filePath'); var path = obj.value; var result = checkFormat(path,['bmp','jpg','jpeg','png']); if(!result){ alert('上传类型错误,请重新上传'); obj.value = ''; } }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* 通过扩展名,检验文件格式。
* @parma filePath{string} 文件路径
* @parma acceptFormat{Array} 允许的文件类型
* <a href="http://www.jobbole.com/members/tdbtx">@result</a> 返回值{Boolen}:true or false
*/
 
function checkFormat(filePath,acceptFormat){
    var resultBool= false,
        ex = filePath.substring(filePath.lastIndexOf('.') 1);
        ex = ex.toLowerCase();
        
    for(var i = 0; i < acceptFormat.length; i ){
      if(acceptFormat[i] == ex){
            resultBool = true;
            break;
      }
    }
    return resultBool;
};
        
function limitTypes(){
    var obj = document.getElementById('filePath');
    var path = obj.value;
    var result = checkFormat(path,['bmp','jpg','jpeg','png']);
    
    if(!result){
        alert('上传类型错误,请重新上传');
        obj.value = '';
    }
}

function selectAll(objSelect) {
            if (objSelect.checked == true) {
                $("input[name='chkId']").attr("checked", true);
                $("input[name='chkAll']").attr("checked", true);
            }
            else if (objSelect.checked == false) {
                $("input[name='chkId']").attr("checked", false);
                $("input[name='chkAll']").attr("checked", false);
            }
        }

/* JS 实行电火花计时器 */

七十四、正则表明式

//验证邮箱 /^w @([0-9a-zA-Z] [.]) [a-z]{2,4}$/ //验证手提式有线电电话机号 /^1[3|5|8|7]d{9}$/ //验证URL /^http://. ./ //验证身份ID编号 /(^d{15}$)|(^d{17}([0-9]|X|x)$)/ //相称字母、数字、中文字符 /^([A-Za-z0-9]|[u4e00-u9fa5])*$/ //相称汉语字符 /[u4e00-u9fa5]/ //相称双字节字符(包罗汉字) /[^x00-xff]/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//验证邮箱
/^w @([0-9a-zA-Z] [.]) [a-z]{2,4}$/
 
//验证手机号
/^1[3|5|8|7]d{9}$/
 
//验证URL
/^http://. ./
 
//验证身份证号码
/(^d{15}$)|(^d{17}([0-9]|X|x)$)/
 
//匹配字母、数字、中文字符
/^([A-Za-z0-9]|[u4e00-u9fa5])*$/
 
//匹配中文字符
/[u4e00-u9fa5]/
 
//匹配双字节字符(包括汉字)
/[^x00-xff]/

  


timeStart = new Date().getTime();
timesEnd = new Date().getTime();
document.getElementById("time").innerHTML = timesEnd - timeStart;

三十九、约束字符数

<input id="txt" type="text">

1
<input id="txt" type="text">

//字符串截取 function getByteVal(val, max) { var returnValue = ''; var byteValLen = 0; for (var i = 0; i < val.length; i ) { if (val[i].match(/[^x00-xff]/ig) != null) byteValLen = 2; else byteValLen = 1; if (byteValLen > max) break; returnValue = val[i]; } return returnValue; } $('#txt').on('keyup', function () { var val = this.value; if (val.replace(/[^x00-xff]/g, "**").length > 14) { this.value = getByteVal(val, 14); } });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//字符串截取
function getByteVal(val, max) {
    var returnValue = '';
    var byteValLen = 0;
    for (var i = 0; i < val.length; i ) { if (val[i].match(/[^x00-xff]/ig) != null) byteValLen = 2; else byteValLen = 1; if (byteValLen > max) break;
        returnValue = val[i];
    }
    return returnValue;
}
 
$('#txt').on('keyup', function () {
    var val = this.value;
    if (val.replace(/[^x00-xff]/g, "**").length > 14) {
        this.value = getByteVal(val, 14);
    }
});

/* js 判定浏览器  */

/* JS 写Cookie */

八十六、验证码倒计时

<input id="send" type="button" value="发送验证码">

1
<input id="send" type="button" value="发送验证码">

// JavaScript var times = 60, // 时间设置60秒 timer = null; document.getElementById('send').onclick = function () { // 计时开头timer = setInterval(function () { times--; if (times <= 0) { send.value = '发送验证码'; clearInterval(timer); send.disabled = false; times = 60; } else { send.value = times '秒后重试'; send.disabled = true; } }, 1000); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// JavaScript
var times = 60, // 时间设置60秒
timer = null;
document.getElementById('send').onclick = function () {
// 计时开始
timer = setInterval(function () {
times--;
if (times <= 0) {
send.value = '发送验证码';
clearInterval(timer);
send.disabled = false;
times = 60;
} else {
send.value = times '秒后重试';
send.disabled = true;
}
}, 1000);
}

var times = 60, timer = null; $('#send').on('click', function () { var $this = $(this); // 计时开头 timer = setInterval(function () { times--; if (times <= 0) { $this.val('发送验证码'); clearInterval(timer); $this.attr('disabled', false); times = 60; } else { $this.val(times '秒后重试'); $this.attr('disabled', true); } }, 1000); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var times = 60,
    timer = null;
 
$('#send').on('click', function () {
    var $this = $(this);
    
    // 计时开始
    timer = setInterval(function () {
        times--;
        
        if (times <= 0) {
            $this.val('发送验证码');
            clearInterval(timer);
            $this.attr('disabled', false);
            times = 60;
        } else {
            $this.val(times '秒后重试');
            $this.attr('disabled', true);
        }
    }, 1000);
});

复制代码 代码如下:


function setCookie(name, value, expires, path, domain) {
if (!expires) expires = -1;
if (!path) path = "/";
var d = "" name "=" value;
var e;
if (expires < 0) {
e = "";
}
else if (expires == 0) {
var f = new Date(1970, 1, 1);
e = ";expires=" f.toUTCString();
}
else {
var now = new Date();
var f = new Date(now.getTime() expires * 1000);
e = ";expires=" f.toUTCString();
}
var dm;
if (!domain) {
dm = "";
}
else {
dm = ";domain=" domain;
}
document.cookie = name "=" value ";path=" path e dm;
};

八十四、时间倒计时

<p id="_lefttime"></p>

1
<p id="_lefttime"></p>

var times = 60, timer = null; $('#send').on('click', function () { var $this = $(this); // 计时最初 timer = setInterval(function () { times--; if (times <= 0) { $this.val('发送验证码'); clearInterval(timer); $this.attr('disabled', false); times = 60; } else { $this.val(times '秒后重试'); $this.attr('disabled', true); } }, 1000); });

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var times = 60,
    timer = null;
 
$('#send').on('click', function () {
    var $this = $(this);
    
    // 计时开始
    timer = setInterval(function () {
        times--;
        
        if (times <= 0) {
            $this.val('发送验证码');
            clearInterval(timer);
            $this.attr('disabled', false);
            times = 60;
        } else {
            $this.val(times '秒后重试');
            $this.attr('disabled', true);
        }
    }, 1000);
});

判断是不是是 IE 浏览器
    if (document.all){
        alert(”IE浏览器”);
    }else{
        alert(”非IE浏览器”);
    }
    if (!!window.ActiveXObject){
        alert(”IE浏览器”);
    }else{
        alert(”非IE浏览器”);
    }
判断是IE几
var isIE=!!window.ActiveXObject;
var isIE6=isIE&&!window.XMLHttpRequest;
var isIE8=isIE&&!!document.documentMode;
var isIE7=isIE&&!isIE6&&!isIE8;
if (isIE){
    if (isIE6){
        alert(”ie6″);
    }else if (isIE8){
        alert(”ie8″);
    }else if (isIE7){
        alert(”ie7″);
    }
}

/* JS 读Cookie */

三十二、倒计时跳转

<div id="showtimes"></div>

1
<div id="showtimes"></div>

// 设置倒计时秒数 var t = 10; // 呈现倒计时秒数 function showTime(){ t -= 1; document.getElementById('showtimes').innerHTML= t; if(t==0){ location.href='error404.asp'; } //每秒试行二遍 showTime() set提姆eout("showTime()",1000); } showTime();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 设置倒计时秒数  
var t = 10;  
 
// 显示倒计时秒数  
function showTime(){  
    t -= 1;  
    document.getElementById('showtimes').innerHTML= t;  
 
    if(t==0){  
        location.href='error404.asp';  
    }  
 
    //每秒执行一次 showTime()  
    setTimeout("showTime()",1000);  
}  
 
showTime();

  


function readCookie(name) {
var nameEQ = name "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i ) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) {
return decodeURIComponent(c.substring(nameEQ.length, c.length))
}
} return null
}

三十二、时间戳、纳秒格式化

function formatDate(now) { var y = now.getFullYear(); var m = now.getMonth() 1; // 注意 JavaScript 月份 1 var d = now.getDate(); var h = now.getHours(); var m = now.getMinutes(); var s = now.getSeconds(); return y "-" m "-" d " " h ":" m ":" s; } var nowDate = new Date(1442978789184); alert(formatDate(nowDate));

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function formatDate(now) {
    var y = now.getFullYear();
    var m = now.getMonth() 1; // 注意 JavaScript 月份 1
    var d = now.getDate();
    var h = now.getHours();
    var m = now.getMinutes();
    var s = now.getSeconds();
    
    return y "-" m "-" d " " h ":" m ":" s;
}
 
var nowDate = new Date(1442978789184);
 
alert(formatDate(nowDate));

/* 推断浏览器 */

/* Ajax 请求 */

三十六、当今日期

var calculateDate = function(){ var date = new Date(); var weeks = ["日","一","二","三","四","五","六"]; return date.getFullYear() "年" (date.getMonth() 1) "月" date.getDate() "日 星期" weeks[date.getDay()]; } $(function(){ $("#dateSpan").html(calculateDate()); });

1
2
3
4
5
6
7
8
9
10
11
12
var calculateDate = function(){
 
    var date = new Date();
    var weeks = ["日","一","二","三","四","五","六"];
 
    return date.getFullYear() "年" (date.getMonth() 1) "月"
    date.getDate() "日 星期" weeks[date.getDay()];
}
 
$(function(){
    $("#dateSpan").html(calculateDate());
});

复制代码 代码如下:


C.ajax = function (args) {
var self = this;
this.options = {
type: 'GET',
async: true,
contentType: 'application/x-www-form-urlencoded',
url: 'about:blank',
data: null,
success: {},
error: {}
};
this.getXmlHttp = function () {
var xmlHttp;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xmlhttp) {
alert('您的浏览器不扶助AJAX');
return false;
}
return xmlhttp;
};
this.send = function () {
C.each(self.options, function (key, val) {
self.options[key] = (args[key] == null) ? val : args[key];
});
var xmlHttp = new self.getXmlHttp();
if (self.options.type.toUpperCase() == 'GET') {
xmlHttp.open(self.options.type, self.options.url (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? '&' : '?') self.options.data)), self.options.async);
}
else {
xmlHttp.open(self.options.type, self.options.url, self.options.async);
xmlHttp.setRequestHeader('Content-Length', self.options.data.length);
}
xmlHttp.setRequestHeader('Content-Type', self.options.contentType);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200 || xmlHttp.status == 0) {
if (typeof self.options.success == 'function') self.options.success(xmlHttp.responseText);
xmlHttp = null;
}
else {
if (typeof self.options.error == 'function') self.options.error('Server Status: ' xmlHttp.status);
}
}
};
xmlHttp.send(self.options.type.toUpperCase() == 'POST' ? self.options.data.toString() : null);
};
this.send();
};

五十四、决断星期六/星期日

<p id="text"></p>

1
<p id="text"></p>

function time(y,m){ var tempTime = new Date(y,m,0); var time = new Date(); var saturday = new Array(); var sunday = new Array(); for(var i=1;i<=tempTime.getDate();i ){ time.setFullYear(y,m-1,i); var day = time.getDay(); if(day == 6){ saturday.push(i); }else if(day == 0){ sunday.push(i); } } var text = y "年" m "月份" "<br />" "周六:" saturday.toString() "<br />" "周日:" sunday.toString(); document.getElementById("text").innerHTML = text; } time(2018,5);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function time(y,m){
    var tempTime = new Date(y,m,0);
    var time = new Date();
    var saturday = new Array();
    var sunday = new Array();
    
    for(var i=1;i<=tempTime.getDate();i ){
        time.setFullYear(y,m-1,i);
        
        var day = time.getDay();
        
        if(day == 6){
            saturday.push(i);
        }else if(day == 0){
            sunday.push(i);
        }
    }
    
    var text = y "年" m "月份" "<br />"
                 "周六:" saturday.toString() "<br />"
                 "周日:" sunday.toString();
                
    document.getElementById("text").innerHTML = text;
}
time(2018,5);

function getOs() {
    if (navigator.userAgent.indexOf("MSIE 8.0") > 0) {
        return "MSIE8";
    }
    else if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
        return "MSIE6";
    }
    else if (navigator.userAgent.indexOf("MSIE 7.0") > 0) {
        return "MSIE7";
    }
    else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) {
        return "Firefox";
    }
    if (navigator.userAgent.indexOf("Chrome") > 0) {
        return "Chrome";
    }
    else {
        return "Other";
    }
}

/* JS StringBuilder 用法 */

八十、AJAX调用错误管理

当 Ajax 调用重临 404 或 500 错误时,就实行错误处理程序。若无概念管理程序,别的的 jQuery 代码或会就此罢工。定义三个大局的 Ajax 错误管理程序

澳门新萄京官方网站 8

  


function StringBuilder() {
this.strings = new Array;
};
StringBuilder.prototype.append = function (str) {
this.strings.push(str);
};
StringBuilder.prototype.toString = function () {
return this.strings.join('');
};

四十豆蔻梢头、链式插件调用

jQuery 允许“链式”插件的方法调用,以缓和屡次询问 DOM 并创办三个 jQuery 对象的经过。

澳门新萄京官方网站 9

通过应用链式,能够修正

澳门新萄京官方网站 10

再有豆蔻梢头种方式是在(前缀$卡塔 尔(英语:State of Qatar)变量中高速缓存成分

澳门新萄京官方网站 11

链式和高速缓存的方法都是 jQuery 中得以让代码变得更加短和更加快的特级做法。

本文在GitHub的地址 Common-code

阅读越来越多

参照小说 『总计』web前端开辟常用代码收拾

1 赞 5 收藏 1 评论

澳门新萄京官方网站 12

/*  JS决断七个日子大小 符合 2011-09-09 与二〇一一-9-9 三种格式的比较  */

/* JS 加载到顶端LoadJS */

复制代码 代码如下:


function loadJS (url, fn) {
var ss = document.getElementsByName('script'),
loaded = false;
for (var i = 0, len = ss.length; i < len; i ) {
if (ss[i].src && ss[i].getAttribute('src') == url) {
loaded = true;
break;
}
}
if (loaded) {
if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
return false;
}
var s = document.createElement('script'),
b = false;
s.setAttribute('type', 'text/javascript');
s.setAttribute('src', url);
s.onload = s.onreadystatechange = function () {
if (!b && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
b = true;
if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
}
};
document.getElementsByTagName('head')[0].appendChild(s);
},
bind: function (objId, eventType, callBack) { //适用于其余浏览器的绑定
var obj = document.getElementById(objId);
if (obj.addEventListener) {
obj.addEventListener(eventType, callBack, false);
}
else if (window.attachEvent) {
obj.attachEvent('on' eventType, callBack);
}
else {
obj['on' eventType] = callBack;
}
}
function JSLoad (args) {
s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", args.url);
s.onload = s.onreadystatechange = function () {
if (!s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
if (typeof args.callback == "function") args.callback(this, args);
s.onload = s.onreadystatechange = null;
try {
s.parentNode && s.parentNode.removeChild(s);
} catch (e) { }
}
};
document.getElementsByTagName("head")[0].appendChild(s);
}

//获得日期值并转形成日期格式,replace(/-/g, "/")是基于表明表明式把日子转形成长日期格式,这样再扩充推断就好判定了
        function ValidateDate() {
            var beginDate = $("#t_datestart").val();
            var endDate = $("#t_dateend").val();
            if (beginDate.length > 0 && endDate.length>0) {
                var sDate = new Date(beginDate.replace(/-/g, "/"));
                var eDate= new Date(endDate.replace(/-/g, "/"));
                if (sDate > eDate) {
                    alert('开始日期要小于甘休日期');
                    return false;
                }
            }
        }

/* 清空 LoadJS 加载到顶端的js引用 */

  


function ClearHeadJs (src) {
var js = document.getElementsByTagName('head')[0].children;
var obj = null;
for (var i = 0; i < js.length; i ) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName('head')[0].removeChild(obj);
};

/* 移除事件 */

/* JS 替换不合法字符主要用在密码验证上面世的异样字符 */

复制代码 代码如下:


function URLencode(sStr) {
return escape(sStr).replace(/ /g, '+').replace(/"/g, '"').replace(/'/g, ''').replace(///g, '/');
};

this.moveBind = function (objId, eventType, callBack) {
    var obj = document.getElementById(objId);
    if (obj.removeEventListener) {
        obj.removeEventListener(eventType, callBack, false);
    }
    else if (window.detachEvent) {
        obj.detachEvent('on' eventType, callBack);
    }
    else {
        obj['on' eventType] = null;
    }
}

/* 按Ctrl Entert 直接交给表单 */

  


document.body.onkeydown = function (evt) {
evt = evt ? evt : (window.event ? window.event : null);
if (13 == evt.keyCode && evt.ctrlKey) {
evt.returnValue = false;
evt.cancel = true;
PostData();
}
};

/* 回车提交 */

/* 获取当前岁月 */

复制代码 代码如下:


function GetCurrentDate() {
var d = new Date();
var y = d.getYear() 1900;
month = add_zero(d.getMonth() 1),
days = add_zero(d.getDate()),
hours = add_zero(d.getHours());
minutes = add_zero(d.getMinutes()),
seconds = add_zero(d.getSeconds());
var str = y '-' month '-' days ' ' hours ':' minutes ':' seconds;
return str;
};
function add_zero(temp) {
if (temp < 10) return "0" temp;
else return temp;
}

$("id").onkeypress = function (event) {
    event = (event) ? event : ((window.event) ? window.event : "")
    keyCode = event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode);
    if (keyCode == 13) {
        $("SubmitLogin").onclick();
    }
}

/* Js 去掉空格方法: */

  


String.prototype.Trim = function()
{ return this.replace(/(^s)|(s$)/g, ""); }
String.prototype.LTrim = function()
{return this.replace(/(^s)/g, "");}
String.prototype.RTrim = function()
{return this.replace(/(s
$)/g, "");}

/* JS 施行放大计时器 */

/* js 动态移除 head 里的 js 援用 */

复制代码 代码如下:


this.ClearHeadJs = function (src) {
var js = document.getElementsByTagName('head')[0].children;
var obj = null;
for (var i = 0; i < js.length; i ) {
if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
obj = js[i];
}
}
document.getElementsByTagName('head')[0].removeChild(obj);
};

timeStart = new Date().getTime();
timesEnd = new Date().getTime();
document.getElementById("time").innerHTML = timesEnd - timeStart;

/* 整个UL 点击事件 加在UL里的onclick里 */

 


function CreateFrom(url, params) {
var f = document.createElement("form");
f.setAttribute("action", url);
for (var i = 0; i < params.length; i ) {
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", params[i].paramName);
input.setAttribute("value", params[i].paramValue);
f.appendChild(input);
}
f.target = "_blank";
document.body.appendChild(f);
f.submit();
};

/* JS 写Cookie */

/* 判定浏览器选取的是哪些 JS 版本 */

复制代码 代码如下:

&#13;
&#13;
var jsversion = 1.0;&#13;
&#13;
<script language="javascript">
var jsversion = 1.0;
</script>
<script language="javascript1.1">
jsversion = 1.1;
</script>
<script language="javascript1.2">
jsversion = 1.2;
</script>
<script language="javascript1.3">
jsversion = 1.3;
</script>
<script language="javascript1.4">
jsversion = 1.4;
</script>
<script language="javascript1.5">
jsversion = 1.5;
</script>
<script language="javascript1.6">
jsversion = 1.6;
</script>
<script language="javascript1.7">
jsversion = 1.7;
</script>
<script language="javascript1.8">
jsversion = 1.8;
</script>
<script language="javascript1.9">
jsversion = 1.9;
</script>
<script language="javascript2.0">
jsversion = 2.0;
</script>
alert(jsversion);

function setCookie(name, value, expires, path, domain) {
    if (!expires) expires = -1;
    if (!path) path = "/";
    var d = "" name "=" value;
    var e;
    if (expires < 0) {
        e = "";
    }
    else if (expires == 0) {
        var f = new Date(1970, 1, 1);
        e = ";expires=" f.toUTCString();
    }
    else {
        var now = new Date();
        var f = new Date(now.getTime() expires * 1000);
        e = ";expires=" f.toUTCString();
    }
    var dm;
    if (!domain) {
        dm = "";
    }
    else {
        dm = ";domain=" domain;
    }
    document.cookie = name "=" value ";path=" path e dm;
};

末段在说几句:厉害工程师相对于普通程序员的优势在于:写出的代码更便于排错,不是风度翩翩把手的代码就不会错,而是高手的代码出了错轻易找。高手的代码可读性一定很好,模块清晰,命名规范,格式工整,关键的地点有注释,出了极其有log,自然轻易排错,即便付出旁人去debug也是比较容易的。

  

【编辑推荐】

/* JS 读Cookie  */

复制代码 代码如下:

function readCookie(name) {
    var nameEQ = name "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i ) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
            return decodeURIComponent(c.substring(nameEQ.length, c.length))
        }
    } return null
}

  

/*  Ajax 请求  */

复制代码 代码如下:

C.ajax = function (args) {
    var self = this;
    this.options = {
        type: 'GET',
        async: true,
        contentType: 'application/x-www-form-urlencoded',
        url: 'about:blank',
        data: null,
        success: {},
        error: {}
    };
    this.getXmlHttp = function () {
        var xmlHttp;
        try {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e) {
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        if (!xmlhttp) {
            alert('您的浏览器不支持AJAX');
            return false;
        }
        return xmlhttp;
    };
    this.send = function () {
        C.each(self.options, function (key, val) {
            self.options[key] = (args[key] == null) ? val : args[key];
        });
        var xmlHttp = new self.getXmlHttp();
        if (self.options.type.toUpperCase() == 'GET') {
            xmlHttp.open(self.options.type, self.options.url (self.options.data == null ? "" : ((/[?]$/.test(self.options.url) ? '&' : '?') self.options.data)), self.options.async);
        }
        else {
            xmlHttp.open(self.options.type, self.options.url, self.options.async);
            xmlHttp.setRequestHeader('Content-Length', self.options.data.length);
        }
        xmlHttp.setRequestHeader('Content-Type', self.options.contentType);
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) {
                if (xmlHttp.status == 200 || xmlHttp.status == 0) {
                    if (typeof self.options.success == 'function') self.options.success(xmlHttp.responseText);
                    xmlHttp = null;
                }
                else {
                    if (typeof self.options.error == 'function') self.options.error('Server Status: ' xmlHttp.status);
                }
            }
        };
        xmlHttp.send(self.options.type.toUpperCase() == 'POST' ? self.options.data.toString() : null);
    };
    this.send();
};

/*  JS StringBuilder 用法  */

复制代码 代码如下:

function StringBuilder() {
    this.strings = new Array;
};
StringBuilder.prototype.append = function (str) {
    this.strings.push(str);
};
StringBuilder.prototype.toString = function () {
    return this.strings.join('');
};

  

/* JS 加载到顶端LoadJS  */

复制代码 代码如下:

function loadJS (url, fn) {
        var ss = document.getElementsByName('script'),
            loaded = false;
        for (var i = 0, len = ss.length; i < len; i ) {
            if (ss[i].src && ss[i].getAttribute('src') == url) {
                loaded = true;
                break;
            }
        }
        if (loaded) {
            if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
            return false;
        }
        var s = document.createElement('script'),
            b = false;
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', url);
        s.onload = s.onreadystatechange = function () {
            if (!b && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                b = true;
                if (fn && typeof fn != 'undefined' && fn instanceof Function) fn();
            }
        };
        document.getElementsByTagName('head')[0].appendChild(s);
    },
    bind: function (objId, eventType, callBack) {  //适用于其他浏览器的绑定
        var obj = document.getElementById(objId);
        if (obj.addEventListener) {
            obj.addEventListener(eventType, callBack, false);
        }
        else if (window.attachEvent) {
            obj.attachEvent('on' eventType, callBack);
        }
        else {
            obj['on' eventType] = callBack;
        }
    }
function JSLoad (args) {
        s = document.createElement("script");
        s.setAttribute("type", "text/javascript");
        s.setAttribute("src", args.url);
        s.onload = s.onreadystatechange = function () {
            if (!s.readyState || s.readyState == "loaded" || s.readyState == "complete") {
                if (typeof args.callback == "function") args.callback(this, args);
                s.onload = s.onreadystatechange = null;
                try {
                    s.parentNode && s.parentNode.removeChild(s);
                } catch (e) { }
            }
        };
        document.getElementsByTagName("head")[0].appendChild(s);
    }

  

/*  清空 LoadJS 加载到最上部的js援引  */

复制代码 代码如下:

function ClearHeadJs  (src) {
        var js = document.getElementsByTagName('head')[0].children;
        var obj = null;
        for (var i = 0; i < js.length; i ) {
            if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
                obj = js[i];
            }
        }
        document.getElementsByTagName('head')[0].removeChild(obj);
    };

  

/*  JS 替换违规字符重要用在密码验证上冒出的出格字符  */

复制代码 代码如下:

function URLencode(sStr) {
    return escape(sStr).replace(/ /g, '+').replace(/"/g, '"').replace(/'/g, ''').replace(///g, '/');
};

  

/*  按Ctrl Entert 直接提交表单   */

复制代码 代码如下:

document.body.onkeydown = function (evt) {
    evt = evt ? evt : (window.event ? window.event : null);
    if (13 == evt.keyCode && evt.ctrlKey) {
        evt.returnValue = false;
        evt.cancel = true;
        PostData();
    }
};

  
/* 获取当前时光  */

复制代码 代码如下:

function GetCurrentDate() {
        var d = new Date();
        var y = d.getYear() 1900;
        month = add_zero(d.getMonth() 1),
        days = add_zero(d.getDate()),
        hours = add_zero(d.getHours());
        minutes = add_zero(d.getMinutes()),
        seconds = add_zero(d.getSeconds());
        var str = y '-' month '-' days ' ' hours ':' minutes ':' seconds;
        return str;
    };
    function add_zero(temp) {
        if (temp < 10) return "0" temp;
        else return temp;
    }

  
/* Js 去掉空格方法:  */

复制代码 代码如下:

String.prototype.Trim = function()
{ return this.replace(/(^s*)|(s*$)/g, ""); }
String.prototype.LTrim = function()
{return this.replace(/(^s*)/g, "");}
String.prototype.RTrim = function()
{return this.replace(/(s*$)/g, "");}

/* js 动态移除 head 里的 js 引用  */

复制代码 代码如下:

this.ClearHeadJs = function (src) {
    var js = document.getElementsByTagName('head')[0].children;
    var obj = null;
    for (var i = 0; i < js.length; i ) {
        if (js[i].tagName.toLowerCase() == "script" && js[i].attributes['src'].value.indexOf(src) > 0) {
            obj = js[i];
        }
    }
    document.getElementsByTagName('head')[0].removeChild(obj);
};

  

/*  整个UL 点击事件  加在UL里的onclick里 */

复制代码 代码如下:

function CreateFrom(url, params) {
     var f = document.createElement("form");
     f.setAttribute("action", url);
     for (var i = 0; i < params.length; i ) {
         var input = document.createElement("input");
         input.setAttribute("type", "hidden");
         input.setAttribute("name", params[i].paramName);
         input.setAttribute("value", params[i].paramValue);
         f.appendChild(input);
     }
     f.target = "_blank";
     document.body.appendChild(f);
     f.submit();
 };

/* 推断浏览器选取的是哪个 JS 版本 */

复制代码 代码如下:

<script language="javascript">
      var jsversion = 1.0;
    </script>
    <script language="javascript1.1">
      jsversion = 1.1;
    </script>
    <script language="javascript1.2">
      jsversion = 1.2;
    </script>
    <script language="javascript1.3">
      jsversion = 1.3;
    </script>
    <script language="javascript1.4">
      jsversion = 1.4;
    </script>
    <script language="javascript1.5">
      jsversion = 1.5;
    </script>
    <script language="javascript1.6">
      jsversion = 1.6;
    </script>
    <script language="javascript1.7">
      jsversion = 1.7;
    </script>
    <script language="javascript1.8">
      jsversion = 1.8;
    </script>
    <script language="javascript1.9">
      jsversion = 1.9;
    </script>
    <script language="javascript2.0">
      jsversion = 2.0;
    </script>
alert(jsversion);

上述便是本文的全部内容了,希望能对我们持有利于,也不枉整理这么久了,呵呵。

你可能感兴趣的篇章:

  • javascript 常用艺术计算
  • Javascript select下拉框操作常用方法
  • javascript常用艺术、属性集结及NodeList 和 HTMLCollection 的浏览器差异
  • javascript中创设对象的两种常用方法
  • JavaScript常用对象的艺术和品质小结
  • Javascript图像管理—为矩阵增添常用艺术
  • jquery和javascript的区分(常用方法比较)
  • JavaScript中常用的四种相互影响方式亲自去做

本文由澳门新萄京官方网站发布于澳门新萄京赌场网址,转载请注明出处:js常用函数二〇一〇,分享前端开辟常用代码片段

关键词: