点击空白区域 关闭弹出层
$(document).mouseup(function(e){
var _con = $("#node_list"); // 设置目标区域
if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
$(".note_menu").click();
}
});
/* Mark 1 的原理:
判断点击事件发生在区域外的条件是:
1. 点击事件的对象不是目标区域本身
2. 事件对象同时也不是目标区域的子元素
*/
DIV居中
var _width = $(window).width();
var _height =$(window).height();
console.log(_width +":_width: _height"+_height);
var div_top = _height/2 - (DIV / 2);
var div_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));
});
function enforceNum(_node) {
_node.live("keyup blur", function() {
$(_node).val($(_node).val().replace(/[^0-9-]+/, ‘‘));
});
}
获取当前日期
function CurentTime() {
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
// var hh = now.getHours(); //时
// var mm = now.getMinutes(); //分
var clock = year + "";
if(month < 10)
clock += "0";
clock += month + "";
if(day < 10)
clock += "0";
clock += day ;
return(clock);
}
随机排序数组
var ss=ran_Arr([0,1,2]);
function ran_Arr(oArr) {
var temp_x; //临时交换数
var tArr = oArr.slice(0);//新数组,复制原数组
var random_x;
for(var i=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;
}
return tArr; //返回新数组
点击滚动到下一个位置
$(".js-order-list").delegate(‘.btn-next‘, ‘click‘, function() {
$("html, body").animate({"scrollTop": (($(this).offset().top)+50) + "px" }, 500, "swing");
});
平滑滚动到锚点
// HTML: //</pre> <h1 id="anchor">Lorem Ipsum</h1> <pre>// <a class="topLink"href="#anchor">Back to Top</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("<div id=\"toTop\" style=\"border:1px solid #444;background:#333;color:#fff;text-align:center;padding:10px 13px 7px 13px;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() { // IMAGE RESIZE $(‘#product_cat_list img‘).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; } }); //$("#contentpage img").show(); // IMAGE RESIZE });
滚动时自动加载内容
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(‘More Characters‘); } 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; });
修复 IE6 PNG 问题
$(
‘.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){ var e=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文件
var oHead = document.getElementsByTagName(‘HEAD‘).item(0);
var oScript= document.createElement("script");
oScript.type = "text/javascript";
oScript.src="jcrop/jquery.Jcrop.min.js";
oHead.appendChild( oScript);
匹配:控制在30个汉字,60个单词以内
function testChar(inputVal) { //去除首尾空格 inputValinputVal = inputVal.replace(/^\s*|\s*$/g,""); //零长字串不作处理 if ( inputVal.length == 0 ) { return false; } //只能匹配数字,字母或汉字 var _match = inputVal.match(/^[a-zA-Z0-9\u4e00-\u9fa5]+$/g); //匹配数字或字母(包括大小写) var codeMatch = inputVal.match(/[a-zA-Z0-9]/g); //匹配汉字 var charMatch = inputVal.match(/[\u4e00-\u9fa5]/g); //数字或字母个数 var codeNum = codeMatch ? codeMatch.length : 0; //汉字个数 var charNum = charMatch ? charMatch.length : 0; //成功 if ( _match && codeNum + 2*charNum <= 60 ) { alert("输入正确!"); return true; } //失败 alert("请控制在30个汉字,60个单词以内"); return false; }
点击Li,切换对应的div
$("body").delegate(".cutover","click",function(i){ $(".tab_menu").find("li").each( function(){ $(this).removeClass("current"); }); var cur= $(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",+new Date()) }) $(ele).on("mouseup",function(){ var longClickTime=300; if(+new Date()-$(this).data("timeStamp")>longClickTime){ $(this),triggle("longclick"); } }) $(ele).on("longclick",function(){ alert("long clicked !"); });
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){ var x=e.pageX-_x;//移动时根据鼠标位置计算控件左上角的绝对位置 var y=e.pageY-_y; $(".drag").css({top:y,left:x});//控件新位置 } }).mouseup(function(){ _move=false; $(".drag").fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明 }); });
显示时间
function time(){ //获得显示时间的div t_div = document.getElementById(‘showtime‘); var now=new Date() //替换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(){ var opts = { lines: 9, // The number of lines to draw length: 0, // The length of each line width: 10, // The line thickness radius: 15, // The radius of the inner circle corners: 1, // Corner roundness (0..1) rotate: 0, // The rotation offset color: ‘#000‘, // #rgb or #rrggbb speed: 1, // Rounds per second trail: 60, // Afterglow percentage shadow: false, // Whether to render a shadow hwaccel: false, // Whether to use hardware acceleration className: ‘spinner‘, // The CSS class to assign to the spinner zIndex: 2e9, // The z-index (defaults to 2000000000) top: ‘auto‘, // Top position relative to parent in px left: ‘auto‘ // Left position relative to parent in px }; var target = document.getElementById(‘foo‘); var spinner = new Spinner(opts).spin(target); })
图片移上,有光圈特效
<img src="../../assets/img/1.jpg" id="img_ii”>
$("#img_ii").mouseover(function() { var e = 0, t = 15, n = null, r = $(this); n = setInterval(function() { e < 223 || t < 238 ? (r.css({ "-webkit-mask": "-webkit-gradient(radial, 20 20, " + e + ", 20 20, " + 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‘, ‘table thead [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(); * * jQuery placeholder, fix for IE6,7,8,9 * @author JENA * @since 20131115.1504 * @website ishere.cn */ var zte_PlaceHolder = { //检测 _check : function(){ return ‘placeholder‘ in document.createElement(‘input‘); }, //初始化 init : function(){ if(!this._check()){ this.fix(); } }, //修复 fix : function(){ jQuery(‘:input[placeholder]‘).each(function(index, element) { var self = $(this), txt = self.attr(‘placeholder‘); self.wrap($(‘<div></div>‘).css({position:‘relative‘, zoom:‘1‘, border:‘none‘, background:‘none‘, padding:‘none‘, margin:‘none‘})); var pos = self.position(), h = self.outerHeight(true), paddingleft = self.css(‘padding-left‘); var holder = $(‘<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内容改变另一个位置的值
var title = $(‘.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(){ var index = $(".dtm-tab1-inner .dtm-tab1-hi").index(this); console.log(index); });
Table增加 行和列
/**
* [addLine 添加列]
*/
function addCol() { console.log("...................addCol..................."); var root = $("tbody"); console.log(root); var allRows = $(root).find(‘td‘); console.log(allRows); var cRowlength = $(allRows).length; console.log(cRowlength); var cRow = $(allRows).eq(cRowlength - 1).clone(); console.log(cRow); $(cRow).appendTo($(‘.daboard-table‘).find("tr")); }
/**
* [addRow 添加行 ]
*/
function addRow() { console.log("...................addRow..................."); var root = $("tbody"); console.log(root); var allRows = $(root).find(‘tr‘); console.log(allRows); var cRowlength = $(allRows).length; console.log(cRowlength); var cRow = $(allRows).eq(cRowlength - 1).clone(); console.log(cRow); $(cRow).appendTo(root); }
div交换位置
var arr = $(‘.data-edt-li‘).find(‘.data-edt‘).toArray();// 把三个div放进数组里面 var temp; // 1 0对调 temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; $(‘.data-edt-li‘).html(arr);
监听输入框值变化
if(document.addEventListener){ // 显示函数 var showInputChange = (function () { var _output = document.getElementById(‘output‘); return function (e) { _output.innerHTML = e.target.value; } })(); document.getElementById(‘myInput‘).addEventListener(‘input‘,showInputChange); }else if(document.attachEvent){ // 显示函数 var showInputChange = (function () { var _output = document.getElementById(‘output‘); return function (e) { if (e.propertyName.toLowerCase() == ‘value‘){ _output.innerHTML = e.srcElement.value; } } })(); document.getElementById(‘myInput‘).attachEvent(‘onpropertychange‘,showInputChange); }
判断input值改变
if(document.addEventListener){ // 显示函数 var showInputChange = (function () { var _output = document.getElementById(‘output‘); returnfunction (e) { _output.innerHTML = e.target.value; } })(); document.getElementById(‘myInput‘).addEventListener(‘input‘,showInputChange); }elseif(document.attachEvent){ // 显示函数var showInputChange = (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="1px solid #"+(~~(Math.random()*(1<<24))).toString(16) })