分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

js 常用代码片段

发布时间:2023-09-06 02:15责任编辑:白小东关键词:js

一、预加载图像

如果你的网页中需要使用大量初始不可见的(例如,悬停的)图像,那么可以预加载这些图像。

  function preloadImages(){

    for(var i=0;i<arguments.length;i++){

      $("<img>").attr(‘arc‘,arguments[i])

    }

  }

  preloadImages()

二、检查图像是否加载

有时为了继续脚本,你可能需要检查图像是否全部加载完毕。

$(‘img‘).load(function(){

  console.log(‘image load successfuI‘)

})

你也可以使用 ID 或 CLASS 替换<img> 标签来检查某个特定的图像是否被加载。

三、自动修复破坏的图像

逐个替换已经破坏的图像链接是非常痛苦的。不过,下面这段简单的代码可以帮助你。

$(‘img‘).on(‘error‘,function(){

  if(!$(this).hasClass(‘brokenImage‘)){

    $(this).prop(‘src‘,‘img/broken.pen‘).addClass(‘brokenImage‘)

  }

})

四、悬停切换

当用户鼠标悬停在可点击的元素上时,可添加类到元素中,反之则移除类。

只需要添加必要的 CSS 即可。更简单的方法是使用 toggleClass() 方法。

五、淡入淡出/显示隐藏

六、鼠标滚轮

$(‘#content‘).on("mousewheel DOMMouseScroll",function(event){

// chrome & ie || // firefox

vardelta=(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‘);

}elseif(delta<0){

console.log(‘mousewheel bottom‘);

}

});

七、鼠标坐标

1、JavaScript实现

X:<input type="text" /> Y:<input type="text" />

functionmousePosition(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

};

}

functionmouseMove(ev){

ev=ev||window.event;

varmousePos=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、HTML实现

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

2、JavaScript实现

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

});

十、阻止冒泡

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

functionisSupportSVG(){

varSVG_NS=‘http://www.w3.org/2000/svg‘;

return!!document.createElementNS&&!!document.createElementNS(SVG_NS,‘svg‘).createSVGRect;

}

console.log(isSupportSVG());

十二、检测浏览器是否支持canvas

functionisSupportCanvas(){

if(document.createElement(‘canvas‘).getContext){

returntrue;

}else{

returnfalse;

}

}

console.log(isSupportCanvas());

十三、检测是否是微信浏览器

functionisWeiXinClient(){

varua=navigator.userAgent.toLowerCase();

if(ua.match(/MicroMessenger/i)=="micromessenger"){

returntrue;

}else{

returnfalse;

}

}

alert(isWeiXinClient());

十四、检测是否移动端及浏览器内核

varbrowser={

versions:function(){

varu=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.+MacOSX/),//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(‘移动端‘);

}

十五、检测是否电脑端/移动端

varbrowser={

versions:function(){

varu=navigator.userAgent,app=navigator.appVersion;

varsUserAgent=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.+MacOSX/),

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

}

十六、检测浏览器内核

functiongetInternet(){

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

十八、电脑端页面全屏显示

functionfullscreen(element){

if(element.requestFullscreen){

element.requestFullscreen();

}elseif(element.mozRequestFullScreen){

element.mozRequestFullScreen();

}elseif(element.webkitRequestFullscreen){

element.webkitRequestFullscreen();

}elseif(element.msRequestFullscreen){

element.msRequestFullscreen();

}

}

fullscreen(document.documentElement);

十九、获得/失去焦点

1、JavaScript实现

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

// JavaScript

window.onload=function(){

varoIpt=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" value="请输入您的注册密码"/>

<input type="password" name="psw" value="" style="display:none;"/>

// jQuery

$("#showPwd").focus(function(){

vartext_value=$(this).val();

if(text_value==‘请输入您的注册密码‘){

$("#showPwd").hide();

$("#password").show().focus();

}

});

$("#password").blur(function(){

vartext_value=$(this).val();

if(text_value==""){

$("#showPwd").show();

$("#password").hide();

}

});

二十、获取上传文件大小

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

// 兼容IE9低版本

functiongetFileSize(obj){

varfilesize;

if(obj.files){

filesize=obj.files[0].size;

}else{

try{

varpath,fso;

path=document.getElementById(‘filePath‘).value;

fso=newActiveXObject("Scripting.FileSystemObject");

filesize=fso.GetFile(path).size;

}

catch(e){

// 在IE9及低版本浏览器,如果不容许ActiveX控件与页面交互,点击了否,就无法获取size

console.log(e.message);// Automation 服务器不能创建对象

filesize=‘error‘;// 无法获取

}

}

returnfilesize;

}

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

1、高版本浏览器

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

2、限制图片

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

3、低版本浏览器

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

/* 通过扩展名,检验文件格式。

* @parma filePath{string} 文件路径

* @parma acceptFormat{Array} 允许的文件类型

* @result 返回值{Boolen}:true or false

*/

functioncheckFormat(filePath,acceptFormat){

varresultBool=false,

ex=filePath.substring(filePath.lastIndexOf(‘.‘)+1);

ex=ex.toLowerCase();

for(vari=0;i<acceptFormat.length;i++){

  if(acceptFormat[i]==ex){

resultBool=true;

break;

  }

}

returnresultBool;

};

functionlimitTypes(){

varobj=document.getElementById(‘filePath‘);

varpath=obj.value;

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

二十三、限制字符数

<input type="text">

//字符串截取

functiongetByteVal(val,max){

varreturnValue=‘‘;

varbyteValLen=0;

for(vari=0;i<val.length;i++){if(val[i].match(/[^\x00-\xff]/ig)!=null)byteValLen+=2;elsebyteValLen+=1;if(byteValLen>max)break;

returnValue+=val[i];

}

returnreturnValue;

}

$(‘#txt‘).on(‘keyup‘,function(){

varval=this.value;

if(val.replace(/[^\x00-\xff]/g,"**").length>14){

this.value=getByteVal(val,14);

}

});

二十四、验证码倒计时

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

}

vartimes=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 ></p>

vartimes=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 ></div>

// 设置倒计时秒数

vart=10;

// 显示倒计时秒数

functionshowTime(){

t-=1;

document.getElementById(‘showtimes‘).innerHTML=t;

if(t==0){

location.href=‘error404.asp‘;

}

//每秒执行一次 showTime()

setTimeout("showTime()",1000);

}

showTime();

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

functionformatDate(now){

vary=now.getFullYear();

varm=now.getMonth()+1;// 注意 JavaScript 月份+1

vard=now.getDate();

varh=now.getHours();

varm=now.getMinutes();

vars=now.getSeconds();

returny+"-"+m+"-"+d+" "+h+":"+m+":"+s;

}

varnowDate=newDate(1442978789184);

alert(formatDate(nowDate));

二十八、当前日期

varcalculateDate=function(){

vardate=newDate();

varweeks=["日","一","二","三","四","五","六"];

returndate.getFullYear()+"年"+(date.getMonth()+1)+"月"+

date.getDate()+"日 星期"+weeks[date.getDay()];

}

$(function(){

$("#dateSpan").html(calculateDate());

});

二十九、判断周六/周日

<p ></p>

functiontime(y,m){

vartempTime=newDate(y,m,0);

vartime=newDate();

varsaturday=newArray();

varsunday=newArray();

for(vari=1;i<=tempTime.getDate();i++){

time.setFullYear(y,m-1,i);

varday=time.getDay();

if(day==6){

saturday.push(i);

}elseif(day==0){

sunday.push(i);

}

}

vartext=y+"年"+m+"月份"+"<br />"

+"周六:"+saturday.toString()+"<br />"

+"周日:"+sunday.toString();

document.getElementById("text").innerHTML=text;

}

time(2018,5);

三十、AJAX调用错误处理

当 Ajax 调用返回 404 或 500 错误时,就执行错误处理程序。如果没有定义处理程序,其他的 jQuer

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved