jQuery技巧
1、禁用頁面的右鍵菜單
$(function () {$(document).bind("contextmenu",function(e){return false;})}); View Code2、新窗口打開頁面
$(function () { // 例子1:href="http://"的超鏈接將會在新窗口打開鏈接 // $("a[href^='http://']").attr("target","_blank"); // 例子2:rel="external"的超鏈接將會在新窗口打開鏈接$("a[rel$='external']").click(function(){this.target="_blank";}); // use // <a href="http://www.cssrain.cn" rel="external">open link</a>}); View Code3、判斷瀏覽器類型
$(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以上")} }); View Code需要注意的是,在jquery1.3版本之后,官方推薦使用$.support來代替$.browser這種檢測方式。
4、輸入框文字獲取和失去焦點
$(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); } }); } View Code5、返回頭部滑動動畫
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; }); View Code6、獲取鼠標位置
$(document).ready(function () { $(document).mousemove(function(e){ $('#XY').html("X : " + e.pageX + " | Y : " + e.pageY); }); }); View Code7、判斷元素是否存在
$(document).ready(function() { if ($('#XY').length){ alert('元素存在!')}else{alert('元素不存在!')} }); View Code8、點擊div也可以跳轉
$(document).ready(function() { $("div").click(function(){ window.location=$(this).find("a").attr("href"); return false; }); }); View Code9、根據瀏覽器大小添加不同樣式
$(document).ready(function() { function checkWindowSize() { if ( $(window).width() > 900 ) { $('body').addClass('large'); }else{ $('body').removeClass('large'); } } $(window).resize(checkWindowSize); }); View Code10、設置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(); }); View Code11、創建自己的選擇器
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><link rel="stylesheet" type="text/css" href="css/zgy.css"><style>#XY1 {width: 560px;height: 300px;background: #aaa;}#XY2 {width: 360px;height: 300px;background: #aaa;}</style> </head> <body> <div class="fz"><div id="XY1" class="box"></div><div id="XY2" class="box"></div> </div> </body> <script src="js/jquery-1.9.1.min.js"></script> <script>$(document).ready(function () {$.extend($.expr[':'], {moreThen500px: function (a) {return $(a).width() > 500;}});$('.box:moreThen500px').click(function () {alert();});}); </script> </html> View Code12、關閉所有動畫效果
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><link rel="stylesheet" type="text/css" href="css/zgy.css"><style>#XY {width: 40px;height: 100px;background: #aaa;}</style> </head> <body> <div class="fz"><button id="XY1" class="box">開始動畫</button><button id="XY2" class="box">關閉動畫</button><button id="XY3" class="box">開啟動畫</button><div id="XY" class="box"></div> </div> </body> <script src="js/jquery-1.9.1.min.js"></script> <script>$(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");} </script> </html> View Code13、檢測鼠標右鍵和左鍵
$(document).ready(function() { $("#XY").mousedown(function(e){alert(e.which) // 1 = 鼠標左鍵 ; 2 = 鼠標中鍵; 3 = 鼠標右鍵 }) }); View Code14、回車提交表單
$(document).ready(function() { $("input").keyup(function(e){if(e.which=="13"){alert("回車提交!")}}) }); View Code15、設置全局ajax參數
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><link rel="stylesheet" type="text/css" href="css/zgy.css"><style>#load {display: none;}</style> </head> <body> <div class="fz"><div id="load">加載中...</div><input type="button" id="send1" value="ajax"/><div id="resText1"></div> </div> </body> <script src="js/jquery-1.9.1.min.js"></script> <script>$(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");}</script> </html> View Code16、獲取選中的下拉框
function getObj() { // var $obj = $('#someElement').find('option:selected'); // 或者var $obj=$("#someElement option:selected");alert($obj.val());} View Code18、使用siblings()來選擇同輩元素
$('#nav li').click(function(){$(this).addClass('active').siblings().removeClass('active'); }); View Code19、個性化鏈接
$(document).ready(function(){$("a[href$='pdf']").addClass("pdf");$("a[href$='zip']").addClass("zip");$("a[href$='psd']").addClass("psd"); }); View Code20、在一段時間之后自動隱藏或關閉元素
$(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); }); View Code21、使用Firefox和Firebug來記錄事件日志
// 在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被隱藏');}); }); View Code22、為任何與選擇器想匹配的元素綁定事件
$(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");});}); View Code23、使用css鉤子
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title><link rel="stylesheet" type="text/css" href="css/zgy.css"><style>.box {width: 200px;height: 200px;margin: 10px;background: #333;}</style> </head> <body> <div class="fz"><div id="rect" class="box"></div> </div> </body> <script src="js/jquery-1.9.1.min.js"></script> <script>/*! Copyright (c) 2010 Burin Asavesna (http://helloburin.com)* Licensed under the MIT License (LICENSE.txt).*/(function ($) {// borderRadius get hooksvar 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. MozBorderRadiusTopleftreturn prefix + "Radius" + direction.charAt(0).toUpperCase() + direction.substr(1).toLowerCase();} else {// e.g. WebKitBorderTopLeftRadius, borderTopLeftRadius, etcreturn 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, bottomleftreturn $.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); </script> </html> View Code24、$.proxy()的使用
$('#panel').fadeIn(function(){// Using $.proxy :$('#panel button').click($.proxy(function(){// this 指向 #panel$(this).fadeOut();},this)); }); View Code25、限制text-area域中的字符的個數
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"){//應用標準的maxLengththis.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); View Code26、本地存儲
本地存儲是HTML5提供的特性之一。它提供了非常簡單的API接口,便于添加你的數據到localStorage全局屬性中,代碼如下:
localStorage.someData="this is going to be saved";
對于老的瀏覽器不支持,可以使用jquery插件 http://plugins.jquery.com/plugin-tags/localstorage
27、解析json數據時報pareseerror錯誤
jquery1.4版本后,采用了更為嚴格的json解析方式,即所有內容都必須要有雙引號,如果升級jquery版本后,ajax加載json報錯,可能就是這個原因。比如:
//1.4之前版本,key沒有引號,這樣沒問題
{
key:"28CATEGORY",
status:"0"
}
//但升級1.4版本后,都必須加上雙引號,格式如下:
{
"key":"28CATEGORY",
"status":"0"
}
28、從元素中去除HTML
(function($) { $.fn.stripHtml = function() { var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi; this.each(function() { $(this).html( $(this).html().replace(regexp,'') ); });return $(this); } })(jQuery); //用法: $('div').stripHtml(); View Code29、擴展String對象的方法
$.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(/</g, '<').replace(/>/g,'>').replace(/"/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() ); }); View Code?
轉載于:https://www.cnblogs.com/zhaojieln/p/4272776.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: 2015 UESTC Winter Tr
- 下一篇: PowerDesigner连接SqlSe