`

jQuery 技巧

阅读更多

 

$(document).ready(function(){  
    $(document).bind("contextmenu",function(e){  
        return false;  
    });  
});

 

   

<a href="http://www.cssrain.cn" >新窗口</a>
<a href="http://www.cssrain.cn" rel="external">新窗口</a>
<a href="29.扩展String对象的方法.html" >当前窗口</a>
<a href="#name">当前窗口</a>
$(document).ready(function() {  
     //例子1: href=”http://”的超链接将会在新窗口打开链接 
     $('a[href^="http://"]').attr("target", "_blank");  
 
     //例子2: rel="external"的超链接将会在新窗口打开链接  
     $("a[rel$='external']").click(function(){  
          this.target = "_blank";  
     });  
});

 

   

$(document).ready(function() {  
	// Firefox 2 and above  
	if ($.browser.mozilla && $.browser.version >= "1.8" ){  
		// do something  
	}    
	// Safari  
	if( $.browser.safari ){  
		// do something  
	}    
	// Chrome  
	if( $.browser.chrome){  
		// do something  
	}    
	// Opera  
	if( $.browser.opera){  
		// do something  
	}    
	// IE6 and below  
	if ($.browser.msie && $.browser.version <= 6 ){  
		alert("ie6")
	}    
	// anything above IE6  
	if ($.browser.msie && $.browser.version > 6){  
		alert("ie6以上")
	}  
});

 

   

<input type="text" class="text1" />

$(document).ready(function() {  
	$("input.text1").val("Enter your search text here.");  
	textFill( $('input.text1') );  
});  
function textFill(input){ //input focus text function  
	var originalvalue = input.val();  
	input.focus( function(){  
		if( $.trim(input.val()) == originalvalue ){
			input.val(''); 
		}  
	}).blur( function(){  
		if( $.trim(input.val()) == '' ){ 
			input.val(originalvalue); 
		}  
	});  
}

 

   

<div style="width:100%;height:800px;"></div>
<a href="#nogo" id="goheader">返回顶部</a>

jQuery.fn.scrollTo = function(speed) {
	var targetOffset = $(this).offset().top;
	$('html,body').stop().animate({scrollTop: targetOffset}, speed);
	return this;
}; 
// use
$("#goheader").click(function(){
	$("body").scrollTo(500);
	return false;
});	

 

  

<div id="XY" ></div>

$(document).ready(function () { 
	$(document).mousemove(function(e){  
		$('#XY').html("X : " + e.pageX + " | Y : " + e.pageY);  
	});
});

 

   

<div id="XY" ></div>

$(document).ready(function() {  
	if ($('#XY').length){  
	   alert('元素存在!')
	}else{
	   alert('元素不存在!')
	}
});

  

   

<div style="width:200px;height:40px;background:#eee;cursor:pointer;">
	<a href="http://www.cssrain.cn">home</a>
</div>

$(document).ready(function() {	
	$("div").click(function(){  
		window.location=$(this).find("a").attr("href"); 
		return false;  
	}); 
});

 

  

body.large{
	font-size:20px;
}
body.large a{
	font-size:20px;
	color:red;
}

<ul>
<li><a title="百&#12288;度" target="_blank" href="http://www.baidu.com/index.php?tn=monline_5_dg">百&#12288;度</a></li>
<li><a title="Google" target="_blank" href="http://i.firefoxchina.cn/parts/google_rdr.html">Google</a></li>
<li><a title="新浪" target="_blank" href="http://www.sina.com.cn/">新浪</a></li>
</ul>


$(document).ready(function() {  
	function checkWindowSize() {  
		if ( $(window).width() > 900 ) {  
			$('body').addClass('large');  
		}else{  
			$('body').removeClass('large');  
		}  
	}  
	$(window).resize(checkWindowSize);  
});

 

   

#XY{
	width:460px;
	height:300px;
	background:#aaa;
}

<div id="XY"></div>

$(document).ready(function() {  
   jQuery.fn.center = function () {  
	  this.css("position","absolute");  
	  this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");  
	  this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");  
	  return this;  
	}  
	//use
	$("#XY").center();  
});

 

  

#XY1{
	width:560px;
	height:300px;
	background:#aaa;
}
#XY2{
	width:360px;
	height:300px;
	background:#aaa;
}

<div id="XY1" class="box"></div>
<div id="XY2" class="box"></div>


$(document).ready(function() {  
   $.extend($.expr[':'], {  
       moreThen500px: function(a) {  
           return $(a).width() > 500;  
      }  
   });  
  $('.box:moreThen500px').click(function() {  
      alert();  
  });  
});

   

   

#XY{
	width:40px;
	height:100px;
	background:#aaa;
}

<button id="XY1" class="box">开始动画</button>
<button id="XY2" class="box">关闭动画</button>
<button id="XY3" class="box">开启动画</button>
<div id="XY" class="box"></div>


$(document).ready(function() {  
	$("#XY1").click(function(){
		animateIt();
	});
	$("#XY2").click(function(){
		jQuery.fx.off = true;
	});
	$("#XY3").click(function(){
		jQuery.fx.off = false;
	});
});

function animateIt() {
	$("#XY").slideToggle("slow");
}

 

   

#XY{
	width:40px;
	height:100px;
	background:#aaa;
}

<div id="XY" class="box"></div>

$(document).ready(function() {  
    $("#XY").mousedown(function(e){
		alert(e.which)  // 1 = 鼠标左键 ; 2 = 鼠标中键; 3 = 鼠标右键
	})
});

 

  

#XY{
	width:40px;
	height:100px;
	background:#aaa;
}

<input type="input" />

$(document).ready(function() {  
     $("input").keyup(function(e){
		    if(e.which=="13"){
			   alert("回车提交!")
		    }
		})
});

 

  

#load{
	display:none;
}

<div id="load">加载中...</div>
<input type="button" id="send1" value="ajax"/>
<div id="resText1"></div>


$(document).ready(function() { 
	$('#send1').click(function() {
		$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",function(data){
					  $("#resText1").empty();
					  $.each(data.items, function( i,item ){
							$("<img/> ").attr("src", item.media.m ).appendTo("#resText1");
							if ( i == 3 ) { 
								return false;
							}
					  });
				 }
		); 
   });

	$.ajaxPrefilter(function( options ) {
		options.global = true;
	});
	$("#load").ajaxStart(function(){
		showLoading(); //显示loading
		disableButtons(); //禁用按钮
	});
	$("#load").ajaxComplete(function(){
		hideLoading(); //隐藏loading
		enableButtons(); //启用按钮
	});

});

function showLoading(){
	$("#load").show();
}
function hideLoading(){
	$("#load").hide();
}
function disableButtons(){
	$("#send1").attr("disabled","disabled");
}
function enableButtons(){
	$("#send1").removeAttr("disabled");
}

 

  

<input type="button" id="send1" value="get" onclick="getObj()"/>
<select id="someElement">
	<option>一班</option>
	<option>二班</option>
	<option>三班</option>
</select>

function getObj(){
	var $obj = $('#someElement').find('option:selected');
	alert( $obj.val() );
}

 

  

<button  >toggle</button>
<input type="checkbox" value="1" />篮球
<input type="checkbox" value="2" />足球
<input type="checkbox" value="3" />羽毛球

var tog = false; 
$('button').click(function(){
    $("input[type=checkbox]").attr("checked",!tog);
    tog = !tog;
});

 

  

li.active{
	font-size:20px;
	color:red;
}

<ul id="nav">
	<li>Google</li>
	<li>百&#12288;度</li>
	<li>新浪</li>
</ul>

/* 不这样做
$('#nav li').click(function(){
    $('#nav li').removeClass('active');
    $(this).addClass('active');
});
*/
//替代做法是
$('#nav li').click(function(){
    $(this).addClass('active')
           .siblings().removeClass('active');
});

 

   

body {
	margin: 10px auto;
	width: 570px;
	font: 75%/120% Arial, Helvetica, sans-serif;
	color: #999999;
}
a {
	color:#333399;
}
a:hover {
	text-decoration: none;
}
a.pdf {
	background: url(img/file-red.gif) no-repeat;
	padding-left: 16px;
}
a.zip {
	background: url(img/file-orange.gif) no-repeat;
	padding-left: 16px;
}
a.psd {
	background: url(img/file-blue.gif) no-repeat;
	padding-left: 16px;
}

<p><a href="http://www.webdesignerwall.com/file/wdw-logo.pdf">PDF file</a> (wdw-logo.pdf)</p>
<p><a href="http://www.webdesignerwall.com/file/wdw-logo.psd">PSD file</a> (wdw-logo.psd)</p>
<p><a href="http://www.webdesignerwall.com/file/wdw-logo.zip">Zip file</a> (wdw-logo.zip)</p>

$(document).ready(function(){
	$("a[href$='pdf']").addClass("pdf");
	$("a[href$='zip']").addClass("zip");
	$("a[href$='psd']").addClass("psd");
});

  

  

<p><button>Run</button></p>
<div class="first">Test</div>

$(document).ready(function(){  
	$("button").click(function() {
		$("div").slideUp(300).delay(3000).fadeIn(400);
    });
	/*
	//这是1.3.2中我们使用setTimeout来实现的方式
	setTimeout(function() {
		$('div').fadeIn(400)
	}, 3000);
	*/
	//而在1.4之后的版本可以使用delay()这一功能来实现的方式
	//$("div").slideUp(300).delay(3000).fadeIn(400);
});

 

  

<p><button>Run</button></p>
<div class="first">Test</div>

// 在firebug上查看
jQuery.log = jQuery.fn.log = function (msg) {
      if (console){
         console.log("%s: %o", msg, this);
      }
      return this;
};
$(document).ready(function(){  
	$("button").click(function() {
		$('#someDiv').hide().log('div被隐藏');
    });
});

 

   

.hover{
	background:#f60;
}

<table >
	<tr>
		<td>1111</td>
		<td>2222</td>
		<td>3333</td>
	</tr>
	<tr>
		<td>1111</td>
		<td>2222</td>
		<td>3333</td>
	</tr>
	<tr>
		<td>1111</td>
		<td>2222</td>
		<td>3333</td>
	</tr>
</table>

$(document).ready(function(){  
	/*
	// 为table里面的td元素绑定click事件,不管td元素是一直存在还是动态创建的
	// jQuery 1.4.2之前使用的方式
	$("table").each(function(){ 
	  $("td", this).live("click", function(){ 
	    $(this).toggleClass("hover"); 
	  }); 
	}); 
	// jQuery 1.4.2 使用的方式
	$("table").delegate("td", "click", function(){ 
	  $(this).toggleClass("hover"); 
	});
	*/
	// jQuery 1.7.1使用的方式
	$("table").on("click","td",function(){ 
	  $(this).toggleClass("hover"); 
	});

});

 

   

.box{
	width:200px;
	height:200px;
	margin:10px;
	background:#333;
}

<div id="rect" class="box"></div>

/*! Copyright (c) 2010 Burin Asavesna (http://helloburin.com)
 * Licensed under the MIT License (LICENSE.txt).
 */
(function($) {
    // borderRadius get hooks
    var div = document.createElement('div'),
        divStyle = div.style,
        support = $.support,
        dirs = "TopLeft TopRight BottomRight BottomLeft".split(" ");

    // WebKit supports "borderRadius" as well as "WebKitBorderRadius", weird
    support.borderRadius =
        divStyle.MozBorderRadius     === ''? 'MozBorderRadius'    :
        (divStyle.MsBorderRadius     === ''? 'MsBorderRadius'     :
        (divStyle.WebkitBorderRadius === ''? 'WebkitBorderRadius' :
        (divStyle.OBorderRadius      === ''? 'OBorderRadius'      :
        (divStyle.borderRadius       === ''? 'BorderRadius'       :
        false))));

    div = null;

    function borderCornerRadius(direction, prefix) {
        prefix = prefix === undefined || prefix === '' ? 'border' : prefix + 'Border';
        if ( support.borderRadius && support.borderRadius == "MozBorderRadius" ) {
            // e.g. MozBorderRadiusTopleft
            return prefix + "Radius" + direction.charAt(0).toUpperCase()+direction.substr(1).toLowerCase();
        } else {
            // e.g. WebKitBorderTopLeftRadius, borderTopLeftRadius, etc
            return prefix + direction + "Radius";
        }
    }

    if ( support.borderRadius && support.borderRadius !== "BorderRadius" ) {
        var vendor_prefix = support.borderRadius.replace('BorderRadius','');
        $.cssHooks.borderRadius = {
            get: function( elem, computed, extra ) {
                // return each of the directions, topleft, topright, bottomright, bottomleft
                return $.map(dirs, function( dir ) {
                    return $.css(elem, borderCornerRadius( dir, vendor_prefix ));
                }).join(" ");
            },
            set: function( elem, value ) {
                // takes in a single value or shorthand (just letting the browser handle this) 
                // e.g. 5px to set all, or 5px 0 0 5px to set left corners
                elem.style[ borderCornerRadius( '', vendor_prefix ) ] = value;
            }
        };

        $.each(dirs, function( i, dir ) {
            $.cssHooks[ "borderRadius" + dir ] = {
                get: function( elem, computed, extra ) {
                    return $.css(elem, borderCornerRadius( dir, vendor_prefix ));
                },
                set: function( elem, value ) {
                    elem.style[ borderCornerRadius( dir, vendor_prefix ) ] = value;
                }
            };
        });

    }

})(jQuery);

//use
$('#rect').css('borderRadius',10);

 

   

<div id="panel" style="display:none">
    <button>Close</button>
</div>

$('#panel').fadeIn(function(){
    // Using $.proxy :
    $('#panel button').click($.proxy(function(){
        // this 指向 #panel
        $(this).fadeOut();
    },this));
});

 

  

<textarea id="mytextarea"></textarea>

jQuery.fn.maxLength = function(max){
	this.each(function(){
		var type = this.tagName.toLowerCase();
		var inputType = this.type? this.type.toLowerCase() : null;
		if(type == "input" && inputType == "text" || inputType == "password"){
			//应用标准的maxLength
			this.maxLength = max;
		}else if(type == "textarea"){
			this.onkeypress = function(e){
				var ob = e || event;
				var keyCode = ob.keyCode;
				var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
				return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
			};
			this.onkeyup = function(){
				if(this.value.length > max){
					this.value = this.value.substring(0,max);
				}
			};
		}
	});
};
//use
$('#mytextarea').maxLength(10);

 

  

<p><a href="#nogo">jQuery</a></p>
</div>

(function($) { 
$.fn.stripHtml = function() { 
  var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; 
  this.each(function() { 
    $(this).html( $(this).html().replace(regexp,'') ); 
  });
  return $(this); 
} 
})(jQuery); 
//用法: 
$('div').stripHtml(); 

 

  

<input type="text" /><button >check</button>
</div>

$.extend(String.prototype, {
isPositiveInteger:function(){
	return (new RegExp(/^[1-9]\d*$/).test(this));
},
isInteger:function(){
	return (new RegExp(/^\d+$/).test(this));
},
isNumber: function(value, element) {
	return (new RegExp(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/).test(this));
},
trim:function(){
	return this.replace(/(^\s*)|(\s*$)|\r|\n/g, "");
},
trans:function() {
	return this.replace(/&lt;/g, '<').replace(/&gt;/g,'>').replace(/&quot;/g, '"');
},
replaceAll:function(os, ns) {
	return this.replace(new RegExp(os,"gm"),ns);
},
skipChar:function(ch) {
	if (!this || this.length===0) {return '';}
	if (this.charAt(0)===ch) {return this.substring(1).skipChar(ch);}
	return this;
},
isValidPwd:function() {
	return (new RegExp(/^([_]|[a-zA-Z0-9]){6,32}$/).test(this)); 
},
isValidMail:function(){
	return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(this.trim()));
},
isSpaces:function() {
	for(var i=0; i<this.length; i+=1) {
	var ch = this.charAt(i);
	if (ch!=' '&& ch!="\n" && ch!="\t" && ch!="\r") {return false;}
	}
	return true;
},
isPhone:function() {
	return (new RegExp(/(^([0-9]{3,4}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0-9]{3,4}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/).test(this));
},
isUrl:function(){
	return (new RegExp(/^[a-zA-z]+:\/\/([a-zA-Z0-9\-\.]+)([-\w .\/?%&=:]*)$/).test(this));
},
isExternalUrl:function(){
	return this.isUrl() && this.indexOf("://"+document.domain) == -1;
}
});

$("button").click(function(){
	alert(   $("input").val().isInteger()  );
});

 

   

1
1
分享到:
评论

相关推荐

    jQuery技巧总结.pdf

    ### jQuery技巧总结 #### 一、简介 ##### 1.1 概述 随着WEB2.0技术的兴起和AJAX思想的普及,各种优秀的JavaScript框架应运而生,其中包括Prototype、YUI、jQuery、MooTools、Bindows以及国内的JSVM框架等。这些...

    15个Jquery 技巧

    ### 15个jQuery技巧深度解析 在前端开发领域,jQuery作为一款优秀的JavaScript库,以其简洁、高效的特点深受开发者喜爱。以下是对“15个Jquery 技巧”文章中的核心知识点进行的深入分析,旨在帮助使用jQuery框架的...

    jQuery技巧大放送

    本篇文章将深入探讨一些实用的jQuery技巧,帮助开发者更高效地利用这个强大的工具。 1. **页面元素的引用** 在jQuery中,我们可以使用`$()`选择器来引用页面上的元素,支持多种方式,如ID(`#id`)、类(`.class`...

    jQuery教程14个实用的jQuery技巧

    ### jQuery教程:14个实用的jQuery技巧详解 #### 技巧一:高效利用jQuery选择器 在网页开发中,选择器是与DOM元素交互的关键工具。jQuery通过强大的选择器功能,让开发者能够轻松地定位到页面中的任何元素。虽然...

    jquery技巧总结(转)

    **jQuery 技巧总结** jQuery 是一款非常流行的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画制作和Ajax交互等任务。自2006年发布以来,jQuery 已经成为 web 开发不可或缺的一部分。这篇总结将探讨一些...

    Jquery技巧(必须掌握)

    在本文中,我们将深入探讨几个必须掌握的jQuery技巧,以提升你的开发效率和代码质量。 首先,确保jQuery已被正确加载是至关重要的。在使用任何jQuery功能之前,应该检查jQuery是否可用。可以通过以下方式来检查: ...

    JQuery技巧学习附带API文档

    **jQuery技巧学习与API文档详解** jQuery是一款广泛应用于前端开发的JavaScript库,它极大地简化了JavaScript的DOM操作、事件处理、动画设计以及Ajax交互。本篇文章将深入探讨jQuery的核心技巧和API,帮助开发者...

    jQuery 技巧总结.zip

    **jQuery 技巧总结** ...通过熟练掌握这些jQuery技巧,开发者可以编写出简洁、高效且易于维护的JavaScript代码,提升网页的交互性和用户体验。不断学习和实践jQuery,能让你在前端开发中更加游刃有余。

    jQuery技巧大放送.rar

    这个名为"jQuery技巧大放送.rar"的压缩包很可能包含了关于如何利用jQuery提升网页开发效率的各种实用技巧和示例。下面我们将深入探讨jQuery的一些核心知识点,以及如何利用它们来实现描述中的下拉菜单和切换菜单功能...

    jQuery 技巧总结

    jQuery 技巧总结,是经验的系统总结,对新手很有帮助,如果你是老手就不要下了,句句实话。jQuery 技巧总结,是经验的系统总结,对新手很有帮助,如果你是老手就不要下了,句句实话。jQuery 技巧总结,是经验的系统总结...

    jquery技巧

    ### jQuery技巧详解 #### 一、简介 ##### 1.1 概述 随着Web 2.0技术的发展,特别是Ajax思想的普及,各种JavaScript框架应运而生,旨在简化前端开发过程,提升开发效率。其中,jQuery因其简洁、易用的特点,在众多...

    jQuery技巧大全.doc

    《jQuery技巧大全》这篇文章主要介绍了jQuery的一些核心技巧和常见用法,帮助读者深入理解并熟练运用jQuery。以下是对这些知识点的详细阐述: 1. **页面元素引用**:jQuery提供了多种方式来选择和引用页面上的元素...

    JQuery技巧(基础)

    **jQuery技巧(基础)** jQuery是一款广泛应用于前端开发的JavaScript库,它简化了HTML文档遍历、事件处理、动画设计和Ajax交互等任务。本文将深入解析jQuery与DOM(Document Object Model)的特点,并分享一些基础...

    jQuery技巧大放送.doc

    这篇文档“jQuery技巧大放送.doc”显然集合了作者在使用jQuery过程中积累的一些实用技巧和经验,旨在帮助开发者提升工作效率和代码质量。下面我们将详细探讨一些可能包含在文档中的jQuery知识点: 1. **选择器**:...

Global site tag (gtag.js) - Google Analytics