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

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

原稿出处: WEBING   

一、预加载图像

假使你的网页中须求利用多量起初不可知的(比如,悬停的)图像,那么能够预加载这几个图像。图片 1

二、检查图疑似否加载

不常为了承袭脚本,你恐怕要求检讨图像是还是不是全体加载达成。图片 2

您也足以行使 ID 或 CLASS
替换<img> 标签来检查有个别特定的图像是不是被加载。

三、自动修复破坏的图像

依次替换已经损坏的图像链接是可怜痛楚的。可是,下边这段简单的代码能够支持你。图片 3

四、悬停切换

当用户鼠标悬停在可点击的要素上时,可增添类到成分中,反之则移除类。图片 4

只需求加上供给的 CSS
就能够。更简便易行的方法是采取 toggleClass() 方法。图片 5

五、淡入淡出/展现遮盖

图片 6

六、鼠标滚轮

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

七、鼠标坐标

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;

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

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

1、HTML实现

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

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

2、JavaScript实现

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

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

九、阻止暗许行为

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

十、阻止冒泡

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

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

十二、检查测量试验浏览器是还是不是协助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 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());

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

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(‘移动端’);
}

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

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

十七、强制移动端页面横屏突显

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

十八、计算机端页面全屏展现

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

十九、得到/失去大旨

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

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

二十、获取上传文件大小

<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(‘file帕特h’).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;
}

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

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/*">

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

二十二、正则表达式

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

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]/

二十三、限制字符数

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

二十四、验证码倒计时

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

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

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

二十五、时间倒计时

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

二十六、倒计时跳转

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

二十八、当前些天子

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

二十九、判定周天/星期天

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

三十、AJAX调用错误管理

当 Ajax 调用重回 404 或 500
错误时,就推行错误管理程序。若无定义管理程序,其余的 jQuery
代码或会就此罢工。定义三个大局的 Ajax 错误管理程序

图片 7

三十一、链式插件调用

jQuery 允许“链式”插件的方法调用,以减轻一再询问 DOM 并创办多个 jQuery
对象的历程。

图片 8

通过应用链式,能够改正

图片 9

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

图片 10

链式和高速缓存的形式都以 jQuery 中能够让代码变得越来越短和越来越快的一流做法。

本文在GitHub的地址 Common-code

翻阅更加多

仿效作品 『总结』web前端开垦常用代码整理

1 赞 5 收藏 1
评论

图片 11

相关文章