jQuery使用技巧

来源:互联网 发布:ubuntu安装软件命令 编辑:程序博客网 时间:2024/06/05 23:44

2017年开张了,朝着自己的小目标前进。梦想一定要有,万一实现了呢! 2天上没有掉馅饼 撸起袖子加油干 努力拼搏才能实现自己的梦想。

1.禁用网页上的右键菜单

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

2.新窗口打开页面

$(document).ready(function(){    $('a[href^="https://www.google.com"]').attr("target","_blank");// href的超链接会在新窗口打开  <a href="https://www.google.com" rel="newwindows">newwindow</a>$("a[rel$='newwindow']").click(function(){        this.target="_blank";    });});

3.判断浏览器的类型

在jQuery 1.3版本之后,官方推荐使用$.support 来代替$.browser
jQuery 1.9版本之后 删除了$.browser, 取而代之的是 $.support 。 在更新的 2.0 版本中,将不再支持 IE 6/7/8。 如果用户需要支持 IE 6/7/8,只能使用 jQuery 1.9。 如果要全面支持 IE,并混合使用 jQuery 1.9 和 2.0, 官方的解决方案是:

<!--[if lt IE 9]>    <script src='jquery-1.9.0.js'></script><![endif]--><!--[if gte IE 9]>    <script src='jquery-2.0.0.js'></script><![endif]-->

jQuery 1.9版本之前判断浏览器的方法如下

$(document).ready(function(){    var $browser=$.browser;    //Firefox 1.8+    if($browser.mozilla&&$browser.version>='1.8'){}    //Safari    if($browser.safari){}    //Chrome    if($browser.chrome){}  //我用谷歌浏览器 x64 Chrome: 56.0.2924.3 这个版本测试 走得是$browser.safari 这个判断,因为谷歌启用了新版的内核,应该是使用苹果的safarie。所以这个判断对新版谷歌有问题    //Opera    if($browser.opera){}    //IE6 -    if($browser.msie&&$browser.version<=6){}    //IE6 +    if($browser.msie&&$browser.version>6){}});

如果使用jQuery 1.9版本之后,建议使用对应的原生javascript的判断浏览器类型:

浏览器代码名称:navigator.appCodeName    浏览器名称:navigator.appName    浏览器版本号:navigator.appVersion    对Java的支持:navigator.javaEnabled()    MIME类型(数组):navigator.mimeTypes    系统平台:navigator.platform    插件(数组):navigator.plugins    用户代理:navigator.userAgent
<script type="text/javascript">        var Sys = {};        var ua = navigator.userAgent.toLowerCase();        var s;        (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :        (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;        //以下进行测试        if (Sys.ie) document.write('IE: ' + Sys.ie);        if (Sys.firefox) document.write('Firefox: ' + Sys.firefox);        if (Sys.chrome) document.write('Chrome: ' + Sys.chrome);        if (Sys.opera) document.write('Opera: ' + Sys.opera);        if (Sys.safari) document.write('Safari: ' + Sys.safari);    </script>

4.文本框文字获取和失去焦点

$(document).ready(function(){    $("input.text").val("请输入文字内容...");    textWaterMark($("input.text"));});function textWaterMark(txtObj){    var origVal=txtObj.val();    txtObj.focus(function(){     if($.trim(txtObj.val())==origVal){            txtObj.val('');        }    }).blur(function(){        if($.trim(txtObj.val())==origVal){            txtObj.val(origVal);        }    });}

5.返回顶部动画

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

6.获取鼠标的位置和左右键

$(document).ready(function(){      //鼠标位置    $(document).mousemove(function(e){      $("#testmousepos").html("X:"+e.pageX+",Y:"+e.pageY);    });    //鼠标左右键    $("#testmousedown").mousedown(function(e){      $(this).html(e.which); //1:鼠标左键;2:鼠标中键(滚轮);3:鼠标右键    });});

js的原生方法,可以参考这篇文章:
http://www.cnblogs.com/dolphinX/archive/2012/10/09/2717119.html

7.判断元素是否存在

$(document).ready(function(){    if($("#id").length>0){} //建议使用>0 的方式,因为$("#id")返回的是一个jquery对象,而length返回的是个数,但是我在个别浏览器测试下只有>0的才走里面的代码,到现在也不知道为何。});

8.点击某些html元素跳转(div span等)

<span><a href="https://www.google.com"></a></span>;$("span").click(function(){    windows.location.href=$(this).find("a").attr("href");    retrun false;});

9.根据浏览器大小添加不同的样式

  jQuery.fn.checkWindowSize=function(){    if($(window).width()>1200){       $('body').addClass('bodyClass');    }    else{     $('body').removeClass('bodyClass');    }    return this;};$(document).ready(function(){   $(window).checkWindowSize();});

10.设置元素在屏幕中心

 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;};$(document).ready(function(){   $("#id").center();});

11.创建属于自己的jQuery选择器

$(document).ready(function(){    $.extend($.expr[":"],{       widthgt100:function(obj){           return $(obj).width()>100;       };    });$("#id:widthgt100").click(function(){});});

12.设置jQuery全局参数

$(document).ready(function(){  //关闭动画效果  jQuery.fx.off=true;   //设置全局进度条 这样就在ajax请求时会自动加载进度条 不必每个方法都写了   var $loading = $("#loading");        var $document = $(document);        $document.ajaxStart(function () {            if ($loading.length>0) {                showLoading();            }        });        $document.ajaxStop(function () {                      if ($loading.length>0) {                hideLoading();            }        });          $document.ajaxComplete(function () {                      if ($loading.length>0) {                hideLoading();            }        });   //简单提一下ajaxStop和ajaxComplete  ajaxStop 是页面所有的ajax结束时 进度条才会关闭,意味着每发送一个请求等效于队列中增加一个showLoading。出现错误时也不会关闭。 而ajaxComplete是页面有一个ajax请求结束进度条就会隐藏,那么有错误的情况下。所以读者要根据自己的实际情况 考虑使用那个全局方法。        $document.ajaxError(function (event, jqxhr, settings, thrownError) {            console.log(settings.url + " " + jqxhr.status + " " + jqxhr.statusText);            console.log(thrownError);        });    //设置某页面全局ajax同步/异步方式         $.ajaxSetup({                    async: false                }); //设置本页请求为同步模式});

还有一部分全局函数可以参考如下网站:
http://www.css88.com/jqapi-1.9/category/ajax/global-ajax-event-handlers/

13.回车提交事件

$(document).ready(function(){    $("#id").keyup(function(e){        if(e.which=="13"){}    });});

14.使用siblings()来选择同辈元素

建议看看这篇文章:http://blog.csdn.net/u010533180/article/details/53816040

//较差的做法$("#id li").click(function(){    $(#id li).removeClass("active");    $(this).addClass("active");});//好的写法$("#id li").click(function(){    $(#id li).addClass("active").siblings().removeClass("active");});

15.控制台输出日志

jQuery.log=jQuery.fn.log=function(msg){    if(console)//考虑到微软家族部分浏览器不支持console函数,坑爹的很    {        console.log("%s:%o",msg,this);    }    return this;};

16.为选择器匹配的元素绑定事件

例如给table里面的td元素绑定click事件,不管td元素是一直存在还是动态创建

建议咨询看看这篇文章第7条内容
http://blog.csdn.net/u010533180/article/details/53816040

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

17.使用css钩子

jquery.cssHooks是1.4.3版本新增的方法,当自定义新的css Hooks时实际上定义的是getter和setter 方法。比如:border-radius 这个圆角属性想要成功应用于firefox、webkit等浏览器,需要增加前缀,例如:-moz-border-radius和-webkit-border-radius。这可以通过自定义css hooks将其封装成统一的接口borderRadius,而不是逐一设置属性。更多cssHooks可以查看
https://github.com/brandonaaron/jquery-cssHooks

$.cssHooks["borderRadius"]={    get:function(elem,computed,extra){     //根据浏览器支持的属性进行获取对应的属性值     //-moz-border-radius  -webkit-border-radius。    },    set:function(elem,value){        //设置属性值    }};$("#id").css("borderRadius",5);

18.限制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"){            //使用空军自身的属性设置            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);                }            };        }    });};//用法$('#mytextarea').maxLength(100);

19.使用HTML5本地存储功能

本地存储是HTML 5 提供的新特性之一,提供了非常简单的API接口,便于添加你的数据到localStoreage全局属性中,便于缓存查找,减少服务器的压力。代码如下:

localStorage.someData="本地缓存内容";

对于一些老的浏览器可能不支持,可以使用jquery 插件来提供支持。
https://plugins.jquery.com/storageapi/

20.从元素中除去HTML

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

21 扩展String方法

 $.extend(String.prototype, {            append: function (str) {                return this.concat(str);            },            /** 删除指定索引位置的字符,索引无效将不删除任何字符 **/            deleteCharAt: function (index) {                if (index < 0 || index >= this.length) {                    return this.valueOf();                }                else if (index == 0) {                    return this.substring(1, this.length);                }                else if (index == this.length - 1) {                    return this.substring(0, this.length - 1);                }                else {                    return this.substring(0, index) + this.substring(index + 1);                }            },            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(/"/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(/^(<_>|){6,32}$/).test(this));            },            isValidMail: function () {                return (new RegExp(/^\w+((-\w+)|(\.\w+))*\@+((\.|-)+)*\.+$/).test(this.trim()));            },            isSpaces: function () {                for (var i = 0, len = this.length; i < len; i++) {                    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(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g)).test(this);            },            isExternalUrl: function () {                return this.isUrl() && this.indexOf("://" + document.domain) == -1;            }        });

也可以把如下链接中的方法扩展到其中
http://www.cnblogs.com/sntetwt/p/4208306.html

10 1
原创粉丝点击