常用js操作:
2015-07-29 11:14
483 查看
点击空白区域关闭弹出层
$(document).mouseup(function(e){
var_con=$("#node_list");//设置目标区域
if(!_con.is(e.target)&&_con.has(e.target).length===0){//Mark1
$(".note_menu").click();
}
});
/*Mark1的原理:
判断点击事件发生在区域外的条件是:
1.点击事件的对象不是目标区域本身
2.事件对象同时也不是目标区域的子元素
*/
DIV居中
var_width=$(window).width();
var_height=$(window).height();
console.log(_width+":_width:_height"+_height);
vardiv_top=_height/2-(DIV/2);
vardiv_left=_width/2-(DIV/2);
console.log(div_top+":div_left:"+div_left);
只能输入数字
onkeyup="(this.v=function(){this.value=this.value.replace(/[^0-9-]+/,'');}).call(this)"
onblur="this.v();"
改进:
$("body").find("input[type='text']").each(function(){
enforceNum($(this));
});
functionenforceNum(_node){
_node.live("keyupblur",function(){
$(_node).val($(_node).val().replace(/[^0-9-]+/,''));
});
}
获取当前日期
functionCurentTime(){
varnow=newDate();
varyear=now.getFullYear();//年
varmonth=now.getMonth()+1;//月
varday=now.getDate();//日
//varhh=now.getHours();//时
//varmm=now.getMinutes();//分
varclock=year+"";
if(month<10)
clock+="0";
clock+=month+"";
if(day<10)
clock+="0";
clock+=day;
return(clock);
}
随机排序数组
varss=ran_Arr([0,1,2]);
functionran_Arr(oArr){
vartemp_x;//临时交换数
vartArr=oArr.slice(0);//新数组,复制原数组
varrandom_x;
for(vari=oArr.length;i>0;i--){
random_x=Math.floor(Math.random()*i);//取得一个随机整数
temp_x=tArr[random_x];
tArr[random_x]=tArr[i-1];
tArr[i-1]=temp_x;
}
returntArr;//返回新数组
点击滚动到下一个位置
$(".js-order-list").delegate('.btn-next','click',function(){
$("html,body").animate({"scrollTop":(($(this).offset().top)+50)+"px"},500,"swing");
});
缩放图片
JS点击空白处关闭弹出层
JS改变当前样式文件
动态加载JS文件
匹配:控制在30个汉字,60个单词以内
点击Li,切换对应的div
JS拖拽DIV
显示时间
Loading加载效果
图片移上,有光圈特效
<imgsrc="../../assets/img/1.jpg"id="img_ii”>
table下input全选
IE兼容PlaceHolder
DIV内容改变另一个位置的值
获取当前被点击的是第几个
/*弹出对应的菜单*/
Table增加行和列
/**
*[addLine添加列]
*/
/**
*[addRow添加行]
*/
div交换位置
监听输入框值变化
在你浏览器的Console(F12)中运行一下,你会发现页面被不同的颜色块高亮
$(document).mouseup(function(e){
var_con=$("#node_list");//设置目标区域
if(!_con.is(e.target)&&_con.has(e.target).length===0){//Mark1
$(".note_menu").click();
}
});
/*Mark1的原理:
判断点击事件发生在区域外的条件是:
1.点击事件的对象不是目标区域本身
2.事件对象同时也不是目标区域的子元素
*/
DIV居中
var_width=$(window).width();
var_height=$(window).height();
console.log(_width+":_width:_height"+_height);
vardiv_top=_height/2-(DIV/2);
vardiv_left=_width/2-(DIV/2);
console.log(div_top+":div_left:"+div_left);
只能输入数字
onkeyup="(this.v=function(){this.value=this.value.replace(/[^0-9-]+/,'');}).call(this)"
onblur="this.v();"
改进:
$("body").find("input[type='text']").each(function(){
enforceNum($(this));
});
functionenforceNum(_node){
_node.live("keyupblur",function(){
$(_node).val($(_node).val().replace(/[^0-9-]+/,''));
});
}
获取当前日期
functionCurentTime(){
varnow=newDate();
varyear=now.getFullYear();//年
varmonth=now.getMonth()+1;//月
varday=now.getDate();//日
//varhh=now.getHours();//时
//varmm=now.getMinutes();//分
varclock=year+"";
if(month<10)
clock+="0";
clock+=month+"";
if(day<10)
clock+="0";
clock+=day;
return(clock);
}
随机排序数组
varss=ran_Arr([0,1,2]);
functionran_Arr(oArr){
vartemp_x;//临时交换数
vartArr=oArr.slice(0);//新数组,复制原数组
varrandom_x;
for(vari=oArr.length;i>0;i--){
random_x=Math.floor(Math.random()*i);//取得一个随机整数
temp_x=tArr[random_x];
tArr[random_x]=tArr[i-1];
tArr[i-1]=temp_x;
}
returntArr;//返回新数组
点击滚动到下一个位置
$(".js-order-list").delegate('.btn-next','click',function(){
$("html,body").animate({"scrollTop":(($(this).offset().top)+50)+"px"},500,"swing");
});
平滑滚动到锚点
//HTML: //</pre> <h1id="anchor">LoremIpsum</h1> <pre>// <aclass="topLink"href="#anchor">BacktoTop</a> $(document).ready(function(){ $("a.topLink").click(function(){ $("html,body").animate({ scrollTop:$($(this).attr("href")).offset().top+"px" },{ duration:500, easing:"swing" }); returnfalse; }); }); $(function(){ $(window).scroll(function(){ if($(this).scrollTop()!=0){ $("#toTop").fadeIn(); }else{ $("#toTop").fadeOut(); } }); $("body").append("<divid=\"toTop\"style=\"border:1pxsolid#444;background:#333;color:#fff;text-align:center;padding:10px13px7px13px;position:fixed;bottom:10px;right:10px;cursor:pointer;display:none;font-family:verdana;font-size:22px;\">^</div>"); $("#toTop").click(function(){ $("body,html").animate({scrollTop:0},800); }); });
缩放图片
$(window).bind("load",function(){ //IMAGERESIZE $('#product_cat_listimg').each(function(){ varmaxWidth=120; varmaxHeight=120; varratio=0; varwidth=$(this).width(); varheight=$(this).height(); if(width>maxWidth){ ratio=maxWidth/width; $(this).css("width",maxWidth); $(this).css("height",height*ratio); height=height*ratio; } varwidth=$(this).width(); varheight=$(this).height(); if(height>maxHeight){ ratio=maxHeight/height; $(this).css("height",maxHeight); $(this).css("width",width*ratio); width=width*ratio; } }); //$("#contentpageimg").show(); //IMAGERESIZE });
滚动时自动加载内容
varloading=false; $(window).scroll(function(){ if((($(window).scrollTop()+$(window).height())+250)>=$(document).height()){ if(loading==false){ loading=true; $('#loadingbar').css("display","block"); $.get("load.php?start="+$('#loaded_max').val(),function(loaded){ $('body').append(loaded); $('#loaded_max').val(parseInt($('#loaded_max').val())+50); $('#loadingbar').css("display","none"); loading=false; }); } } }); $(document).ready(function(){ $('#loaded_max').val(50); });
检测密码强度
$('#pass').keyup(function(e){ varstrongRegex=newRegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$","g"); varmediumRegex=newRegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$","g"); varenoughRegex=newRegExp("(?=.{6,}).*","g"); if(false==enoughRegex.test($(this).val())){ $('#passstrength').html('MoreCharacters'); }elseif(strongRegex.test($(this).val())){ $('#passstrength').className='ok'; $('#passstrength').html('Strong!'); }elseif(mediumRegex.test($(this).val())){ $('#passstrength').className='alert'; $('#passstrength').html('Medium!'); }else{ $('#passstrength').className='error'; $('#passstrength').html('Weak!'); } returntrue; });
修复IE6PNG问题
$(
'.pngfix'
).each(
function
(){
$(
this
).attr(
'writing-mode'
,
'tb-rl'
);
$(
this
).css(
'background-image'
,
'none'
);
$(
this
).css(
'filter'
,
'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="scale")'
);
});
隔行换色
$('div:odd').css("background-color","#F4F4F8");
$('div:even').css("background-color","#EFF1F1");
JS点击空白处关闭弹出层
/*用户登录后的下拉JS*/
$(function(){
$(".wrapper-dropdown-3>span").click(function(event){
vare=window.event||event;
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble=true;
}
$(".wrapper-dropdown-3").toggleClass('active');
});
document.onclick=function(){
$('.wrapper-dropdown-3').removeClass('active');
};
});
/*用户登录后的下拉样式end*/
JS改变当前样式文件
$("#selectStyle").change(function(){
$("#styleSrc").attr("href",$(this).val());
});
动态加载JS文件
varoHead=document.getElementsByTagName('HEAD').item(0);
varoScript=document.createElement("script");
oScript.type="text/javascript";
oScript.src="jcrop/jquery.Jcrop.min.js";
oHead.appendChild(oScript);
匹配:控制在30个汉字,60个单词以内
functiontestChar(inputVal)
{
//去除首尾空格
inputValinputVal=inputVal.replace(/^\s*|\s*$/g,"");
//零长字串不作处理
if(inputVal.length==0)
{
returnfalse;
}
//只能匹配数字,字母或汉字
var_match=inputVal.match(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/g);
//匹配数字或字母(包括大小写)
varcodeMatch=inputVal.match(/[a-zA-Z0-9]/g);
//匹配汉字
varcharMatch=inputVal.match(/[\u4e00-\u9fa5]/g);
//数字或字母个数
varcodeNum=codeMatch?codeMatch.length:0;
//汉字个数
varcharNum=charMatch?charMatch.length:0;
//成功
if(_match&&codeNum+2*charNum<=60)
{
alert("输入正确!");
returntrue;
}
//失败
alert("请控制在30个汉字,60个单词以内");
returnfalse;
}
点击Li,切换对应的div
$("body").delegate(".cutover","click",function(i){
$(".tab_menu").find("li").each(function(){
$(this).removeClass("current");
});
varcur=$(this).index();
$(this).addClass("current");
$(".tab_box").find("div").each(function(){
$(this).hide();
});
$(".tab_box").find("div").eq(cur).show();
});
JS判断长按某个按钮
$(ele).on("mousedown",function(){
$(this).data("timeStamp",+newDate())
})
$(ele).on("mouseup",function(){
varlongClickTime=300;
if(+newDate()-$(this).data("timeStamp")>longClickTime){
$(this),triggle("longclick");
}
})
$(ele).on("longclick",function(){
alert("longclicked!");
});
JS拖拽DIV
//模块拖拽
$(function(){
var_move=false;//移动标记
var_x,_y;//鼠标离控件左上角的相对位置
$(".drag").click(function(){
//alert("click");//点击(松开后触发)
}).mousedown(function(e){
_move=true;
_x=e.pageX-parseInt($(".drag").css("left"));
_y=e.pageY-parseInt($(".drag").css("top"));
$(".drag").fadeTo(20,0.5);//点击后开始拖动并透明显示
});
$(document).mousemove(function(e){
if(_move){
varx=e.pageX-_x;//移动时根据鼠标位置计算控件左上角的绝对位置
vary=e.pageY-_y;
$(".drag").css({top:y,left:x});//控件新位置
}
}).mouseup(function(){
_move=false;
$(".drag").fadeTo("fast",1);//松开鼠标后停止移动并恢复成不透明
});
});
显示时间
functiontime(){
//获得显示时间的div
t_div=document.getElementById('showtime');
varnow=newDate()
//替换div内容
t_div.innerHTML="现在是"+now.getFullYear()
+"年"+(now.getMonth()+1)+"月"+now.getDate()
+"日"+now.getHours()+"时"+now.getMinutes()
+"分"+now.getSeconds()+"秒";
//等待一秒钟后调用time方法,由于settimeout在time方法内,所以可以无限调用
setTimeout(time,1000);
}
Loading加载效果
$(function(){
varopts={
lines:9,//Thenumberoflinestodraw
length:0,//Thelengthofeachline
width:10,//Thelinethickness
radius:15,//Theradiusoftheinnercircle
corners:1,//Cornerroundness(0..1)
rotate:0,//Therotationoffset
color:'#000',//#rgbor#rrggbb
speed:1,//Roundspersecond
trail:60,//Afterglowpercentage
shadow:false,//Whethertorenderashadow
hwaccel:false,//Whethertousehardwareacceleration
className:'spinner',//TheCSSclasstoassigntothespinner
zIndex:2e9,//Thez-index(defaultsto2000000000)
top:'auto',//Toppositionrelativetoparentinpx
left:'auto'//Leftpositionrelativetoparentinpx
};
vartarget=document.getElementById('foo');
varspinner=newSpinner(opts).spin(target);
})
图片移上,有光圈特效
<imgsrc="../../assets/img/1.jpg"id="img_ii”>
$("#img_ii").mouseover(function(){
vare=0,
t=15,
n=null,
r=$(this);
n=setInterval(function(){
e<223||t<238?(r.css({
"-webkit-mask":"-webkit-gradient(radial,2020,"+e+",2020,"+t+",from(rgb(0,0,0)),color-stop(0.5,rgba(0,0,0,0.2)),to(rgb(0,0,0)))"
}),e++,t++):clearInterval(n)
},1)
})
table下input全选
$(document).on('change','tablethead[type="checkbox"]',function(e){
e&&e.preventDefault();
var$table=$(e.target).closest('table'),$checked=$(e.target).is(':checked');
$('tbody[type="checkbox"]',$table).prop('checked',$checked);
});
IE兼容PlaceHolder
//执行JPlaceHolder
zte_PlaceHolder.init();
*
*jQueryplaceholder,fixforIE6,7,8,9
*@authorJENA
*@since20131115.1504
*@websiteishere.cn
*/
varzte_PlaceHolder={
//检测
_check:function(){
return'placeholder'indocument.createElement('input');
},
//初始化
init:function(){
if(!this._check()){
this.fix();
}
},
//修复
fix:function(){
jQuery(':input[placeholder]').each(function(index,element){
varself=$(this),txt=self.attr('placeholder');
self.wrap($('<div></div>').css({position:'relative',zoom:'1',border:'none',background:'none',padding:'none',margin:'none'}));
varpos=self.position(),h=self.outerHeight(true),paddingleft=self.css('padding-left');
varholder=$('<span></span>').text(txt).css({position:'absolute',left:'30px',top:'20px',height:h,lienHeight:h,paddingLeft:paddingleft,color:'#aaa'}).appendTo(self.parent());
self.focusin(function(e){
holder.hide();
}).focusout(function(e){
if(!self.val()){
holder.show();
}
});
holder.click(function(e){
holder.hide();
self.focus();
});
});
}
};
DIV内容改变另一个位置的值
vartitle=$('.tooltip-inner');
title.bind('DOMNodeInserted',function(e){
$(this).parents(".dtm-edtitm-con").find(".cpt-txipt").find("input").val($(this).html());
});
获取当前被点击的是第几个
/*弹出对应的菜单*/
$(".dtm-tab1-inner.dtm-tab1-hi").click(function(){
varindex=$(".dtm-tab1-inner.dtm-tab1-hi").index(this);
console.log(index);
});
Table增加行和列
/**
*[addLine添加列]
*/
functionaddCol(){
console.log("...................addCol...................");
varroot=$("tbody");
console.log(root);
varallRows=$(root).find('td');
console.log(allRows);
varcRowlength=$(allRows).length;
console.log(cRowlength);
varcRow=$(allRows).eq(cRowlength-1).clone();
console.log(cRow);
$(cRow).appendTo($('.daboard-table').find("tr"));
}
/**
*[addRow添加行]
*/
functionaddRow(){
console.log("...................addRow...................");
varroot=$("tbody");
console.log(root);
varallRows=$(root).find('tr');
console.log(allRows);
varcRowlength=$(allRows).length;
console.log(cRowlength);
varcRow=$(allRows).eq(cRowlength-1).clone();
console.log(cRow);
$(cRow).appendTo(root);
}
div交换位置
vararr=$('.data-edt-li').find('.data-edt').toArray();//把三个div放进数组里面
vartemp;
//10对调
temp=arr[0];
arr[0]=arr[1];
arr[1]=temp;
$('.data-edt-li').html(arr);
监听输入框值变化
if(document.addEventListener){
//显示函数
varshowInputChange=(function(){
var_output=document.getElementById('output');
returnfunction(e){
_output.innerHTML=e.target.value;
}
})();
document.getElementById('myInput').addEventListener('input',showInputChange);
}elseif(document.attachEvent){
//显示函数
varshowInputChange=(function(){
var_output=document.getElementById('output');
returnfunction(e){
if(e.propertyName.toLowerCase()=='value'){
_output.innerHTML=e.srcElement.value;
}
}
})();
document.getElementById('myInput').attachEvent('onpropertychange',showInputChange);
}
判断input值改变
if(document.addEventListener){
//显示函数
varshowInputChange=(function(){
var_output=document.getElementById('output');
returnfunction(e){
_output.innerHTML=e.target.value;
}
})();
document.getElementById('myInput').addEventListener('input',showInputChange);
}elseif(document.attachEvent){
//显示函数varshowInputChange=(function(){
var_output=document.getElementById('output');
returnfunction(e){
if(e.propertyName.toLowerCase()=='value'){
_output.innerHTML=e.srcElement.value;
}
}
})();
document.getElementById('myInput').attachEvent('onpropertychange',showInputChange);
}
在你浏览器的Console(F12)中运行一下,你会发现页面被不同的颜色块高亮
[].forEach.call($$("*"),function(a){
a.style.outline="1pxsolid#"+(~~(Math.random()*(1<<24))).toString(16)
})
相关文章推荐
- 原生Js封装的产品图片360度展示
- JavaScript中的cacheStorage使用详解
- Js动态获取iframe子页面的高度总结
- JSP的基本构成详解
- JS - 跳转页面
- jsp预览本地上传图片
- Javascript offsetLeft详情
- jstack(查看线程)、jmap(查看内存)和jstat(性能分析)命令
- js 正则表达式之test函数讲解
- 浅谈Javascript数组的使用
- JS - 提示是否删除
- JSP入门
- SiteMesh在JSP中的页面装饰
- 浅谈Javascript数组索引
- JSP中的三大指令,详细阐述Page、include指令如何应用
- JavaScript中的原型和继承
- JS ZTREE 的用法
- 时序js插件cubism使用
- JS中showModalDialog 详细使用
- JSON——李炎灰js笔记