您的位置:时时app平台注册网站 > web前端 > 26个常用JavaScript方法集锦【彩世界网址】

26个常用JavaScript方法集锦【彩世界网址】

2019-10-13 21:51

十三、检查评定是不是是微信浏览器

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());

  
/* 获取当前时光  */

六、鼠标滚轮

$('#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');
    }
});

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

二十三、限制字符数

<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 加载到顶上部分LoadJS  */

享用前端开拓常用代码片段

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

初藳出处: WEBING   

复制代码 代码如下:

十一、检验浏览器是不是辅助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());

/* 判别浏览器选拔的是哪位 JS 版本 */

三十、AJAX调用错误管理

当 Ajax 调用再次回到 404 或 500 错误时,就举行错误管理程序。若无概念管理程序,别的的 jQuery 代码或会就此罢工。定义二个大局的 Ajax 错误管理程序

彩世界网址 1

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

2、限制图片

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

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

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;
}

二十九、判别星期日/周天

<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);

  

九、阻止暗中同意行为

// 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();
});

复制代码 代码如下:

四、悬停切换

当顾客鼠标悬停在可点击的成分上时,可加多类到元素中,反之则移除类。彩世界网址 2

只须求丰盛须要的 CSS 就能够。更简明的艺术是选取 toggleClass() 方法。彩世界网址 3

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

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

$( 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();

$("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();
    }
}

二十二、正则表明式

//验证邮箱 /^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]/

获得url中的参数

2、JavaScript实现

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

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

复制代码 代码如下:

1、高版本浏览器

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

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

复制代码 代码如下:

彩世界网址 4

复制代码 代码如下:

十九、得到/失去大旨

复制代码 代码如下:

十二、检查实验浏览器是还是不是帮忙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());

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 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浏览器  
    }    
}

/* 推断浏览器 */

二十六、倒计时跳转

<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() setTimeout("showTime()",一千); } 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();

复制代码 代码如下:

二十八、当明日子

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());
});

 

一、预加载图像

假定你的网页中须要选取大批量起头不可以看到的(比方,悬停的)图像,那么能够预加载那么些图像。彩世界网址 5

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);
            }
        }

七、鼠标坐标

/* 字符串截取方法  */

十四、检查实验是或不是移动端及浏览器内核

var browser = { versions: function() { var u = navigator.userAgent; return { trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWeb基特') > -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('移动端');
}

上述就是本文的全部内容了,希望能对大家全数助于,也不枉整理这么久了,呵呵。

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);
});

复制代码 代码如下:

五、淡入淡出/彰显掩盖

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;
    }
}

十五、检查测量试验是还是不是计算机端/移动端

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/";
}

复制代码 代码如下:

三、自动修复破坏的图像

梯次替换已经磨损的图像链接是老大难熬的。不过,上面这段简单的代码能够扶植您。彩世界网址 6

/* JS 实施定时器 */

二十、获取上传文件大小

<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;
}

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
}

3、低版本浏览器

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

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

/* 通过扩大名,核实文件格式。 * @parma filePath{string} 文件路线 * @parma acceptFormat{Array} 允许的文件类型 * <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 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;
};

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";
        }
    };
}

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, "");}

二、检查图疑似否加载

有时候为了承袭脚本,你可能须要检查图疑似否全部加载完成。彩世界网址 7

您也能够接纳 ID 或 CLASS 替换<img> 标签来检查有些特定的图疑似否被加载。

/*   全选/全不选  */

十、阻止冒泡

// 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();
});

复制代码 代码如下:

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 写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);
});

/* js 判别浏览器  */

二十七、时间戳、阿秒格式化

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));

复制代码 代码如下:

二十一、限制上传文件类型

  

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 "";
}

三十一、链式插件调用

jQuery 允许“链式”插件的点子调用,以缓慢化解反复询问 DOM 并创办三个 jQuery 对象的长河。

彩世界网址 8

通过应用链式,可以改良

彩世界网址 9

再有一种情势是在(前缀$)变量中高速缓存成分

彩世界网址 10

链式和高速缓存的点子都以 jQuery 中能够让代码变得越来越短和越来越快的特等做法。

本文在GitHub的地址 Common-code

阅读越多

参照他事他说加以考察作品 『计算』web前端开辟常用代码整理

1 赞 5 收藏 1 评论

彩世界网址 11

  

二十五、时间倒计时

<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); } }, 一千); });

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 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);
    }

1、HTML实现

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

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

复制代码 代码如下:

十八、计算机端页面全屏突显

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);

复制代码 代码如下:

复制代码 代码如下:

复制代码 代码如下:

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

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();

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

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";
    }
}

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

复制代码 代码如下:

看清是或不是是 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″);
    }
}

<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 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);
    };

复制代码 代码如下:

  

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 绑定事件 适用于其余浏览器的要素绑定  */

你或然感兴趣的篇章:

  • javascript 常用艺术计算
  • Javascript select下拉框操作常用方法
  • javascript常用艺术、属性群集及NodeList 和 HTMLCollection 的浏览器差距
  • javascript中创造对象的二种常用方法
  • JavaScript常用对象的主意和天性小结
  • Javascript图像拍卖—为矩阵增添常用艺术
  • jquery和javascript的区分(常用方法对比)
  • JavaScript中常用的四种互动格局亲自过问

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

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的版本 */

  

/*  JS推断五个日子大小 切合 二零一一-09-09 与二〇一一-9-9 二种格式的相比较  */

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;
}

复制代码 代码如下:

复制代码 代码如下:

//得到日期值并转化成日期格式,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;
                }
            }
        }

  

复制代码 代码如下:

复制代码 代码如下:

/*  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('');
};

复制代码 代码如下:

  

复制代码 代码如下:

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

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 方法,今日记下,以便未来查询

  

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;
};

/* 手提式有线电电话机类型剖断 */

  

/* 再次回到字符串长度,哥们计数为2  */

  

  

复制代码 代码如下:

复制代码 代码如下:

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);
};

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();
};

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)),
}

复制代码 代码如下:

/*  Ajax 请求  */

/* JS 读Cookie  */

  

/*  JS 替换违法字符首要用在密码验证下边世的奇特字符  */

/* 回车提交 */

  

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

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;
    }

  

本文由时时app平台注册网站发布于web前端,转载请注明出处:26个常用JavaScript方法集锦【彩世界网址】

关键词: