Jquery实用代码片段(转)

1、把所有带有#的空链接换成不友情的链接

    $('a[href="#"]').each(function() {   
        $(this).attr('href', 'javascript:void(0)')   
    });  

2、jQuery全选与取消全选插件

(function($){   
    $.fn.checkall = function(options){   
        var defaults = {chname:"checkname[]", callback:null},   
            options = $.extend(defaults, options),   
            $obj = $(this),   
            $items = $("input[name='"+options.chname+"']"),   
            checkedItem = 0;   
        $items.click(function(){   
            if($items.filter(":checked").length === $items.length){   
                $obj.attr("checked",true);   
            }else{   
                $obj.removeAttr("checked");   
            }   
            checkedItem = $items.filter(":checked").length;   
            if(typeof options.callback === "function") options.callback(checkedItem);   
        });   
        return $obj.each(function(){   
            $(this).click(function(){   
                if($(this).attr("checked")){   
                    $items.attr("checked",true);   
                }else{   
                    $items.removeAttr("checked");   
                }   
                checkedItem = $items.filter(":checked").length;   
                if(typeof options.callback === "function") options.callback(checkedItem);   
            });   
        });   
    }   
})(jQuery);
JS
3、滚动条自动滚到顶部方法
    $("html,body").animate({scrollTop: 0}, "slow");  
4、滚动条自动滚到底部方法
var s = $("body").height()-$(window).height();   
$("html,body").animate({scrollTop: s}, "slow");
5、jQuery自动根据图片高度宽度缩
    jQuery.fn.ImageAutoSize = function(width,height){   
        $(“img”,this).each(function(){   
        var image = $(this);   
            if(image.width()>width){   
                image.width(width);   
                image.height(width/image.width()*image.height());   
            }   
            if(image.height()>height){   
                image.height(height);   
                image.width(height/image.height()*image.width());   
            }   
        });   
    }  
调用:先引用上面的脚本或将上页的脚本放入自己的JS库,然后只要再加 $(function(){ $(“图片组所在的容器”).ImageAutoSize(限制最大宽,限制最大高);});
 
6、JQuery IFrame框架高度自适应(支持嵌套–兼容IE,ff,safafi,chrome)
$("#IframeID").load(function() {    
    $(this).height($(this).contents().height());   
})  
有一点需要注意的,我也在调试的时候才发现的,耽误了不少时间。就是绑定事件必须在iframe加载完毕之前绑定,否则不会执行。
以下是jQuery,load事件的概述
  • 在每一个匹配元素的load事件中绑定一个处理函数。
  • 如果绑定给window对象,则会在所有内容加载后触发,包括窗口,框架,对象和图像。如果绑定在元素上,则当元素的内容加载完毕后触发。
注意:只有当在这个元素完全加载完之前绑定load的处理函数,才会在他加载完后触发。如果之后再绑定就永远不会触发了。所以不要在$(document).ready()里绑定load事件,因为jQuery会在所有DOM加载完成后再绑定load事件。

7. 使用jQuery来切换样式表

$("link[media='screen']").attr("href", "Alternative.css");

8.jQuery检测浏览器类型

(if( $.browser.safari))
    (if ($.browser.msie && $.browser.version > 6 ))
        (if ($.browser.msie && $.browser.version <= 6 ))
            (if ($.browser.mozilla && $.browser.version >= '1.8' ))

9.jQuery验证某个元素是否为空

if ($("#Demo").html()) { //null;}

10. jQuery从集合中获得索引值

$("ul > li").click(function () {
     var index = $(this).prevAll().length;
});

11.jQuery选择被选中的option元素

$("#someElement").find("option:selected");

12. jQuery为选择器绑定方法

$("table").delegate("td", "hover", function(){
     $(this).toggleClass("hover");
});    //1.42版后,delegate替代live,因为它们提供了更好的上下文支持

13. jQuery自动滚动到页面中的某区域(可以看做一个小插件)

jQuery.fn.Autoscroll = function(sel) {
 $('html,body').animate(
  {scrollTop: $(sel).offset().top},500
 );
}      //调用:$("#area_name").Autoscroll();

14. jQuery限制"TextArea"域中的字符数(可以看做一个小插件)

 (function($) {
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);
     }
    };
   }
 });
})(jQuery);  //调用:$('#macoArea").maxLength(500);
JS

15. jQuery判断某个元素是否可见

if($("#macoArea").is(":visible") == "true") { //少年,别跑 }

16. jQuery元素居中显示(可以看做一个小插件)

(function($) {
 jQuery.fn.center = function () {
  this.css('position','absolute');
   this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
   this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
   return this;
 }
})(jQuery);  //调用:$("#macoArea").center();

17. jQuery使用.siblings()选择同辈元素

// 少年,你是否这样操作过
$('#nav li').click(function(){
 $("#macoArea li").removeClass("current");
 $(this).addClass("current");
});
//这样做是不是会更好呢
$("#nav li").click(function(){
 $(this).addClass("current").siblings().removeClass("current");
});

18. jQuery操作复选框全选反选

var sta = false; //你懂,全局东东
$('a').click(function() {
 $("input[type=checkbox]").attr("checked",!sta);
 sta = !sta;
});

19. jQuery获得鼠标光标位置x和y

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

20. jQuery解析XML

function ParseXml(xml) {
 $(xml).find("Node").each(function(){
  $("#macoArea").append($(this).attr("Author") + "");
 );
}

21. jQuery判断图像是否被完全加载进来

$('#demoImg').attr("src", "demo.jpg").load(function() {
 alert("是的,你看到的是真的");
});

22. jQuery让Cookie过期

var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie("example", "foo", { expires: date });;

23. jQuery禁止鼠标右键

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

24.JQuery智能检测判断各种浏览器的类型及其版本信息,可以检测safari,chrome,firefox,ie等主流的浏览器的类型和版本。

$(function() {   
    if ($.browser.msie && ($.browser.version == "6.0")) {   
        alert("<img src='browser/IE.png'>This is MS IE " + $.browser.version);   
    } else if ($.browser.msie && ($.browser.version == "7.0")) {   
        alert("<img src='browser/IE.png'>This is MS IE " + $.browser.version);   
    } else if ($.browser.msie && ($.browser.version == "8.0")) {   
        alert("This is MS IE " + $.browser.version);   
    } else if ($.browser.msie && ($.browser.version == "9.0")) {   
        $("#browser").html("This is MS IE " + $.browser.version);   
    } else if ($.browser.safari) {   
        $("#browser").html("<This is safari!");   
    } else if ($.browser.webkit) {   
        $("#browser").html("This is chrome!");   
    } else if ($.browser.mozilla) {   
        $("#browser").html("This is firefox!");   
    } else if ($.browser.opera) {   
        $("#browser").html("This is opera");   
    } else {   
        $("#browser").html("i don't konw!");   
    }   
}) 
JS

25. Jquery限制输入框内容长度,中文占2个字符长度

    $(function() {   
        $("#txt").bind("keyup change",   
        function() {   
            var len = $(this).val();   
            var total = 0;   
            var han = 0;   
            for (i = 0; i < len.length; i++) {   
                if (len[i].match(/[^\x00-\xff]/ig) != null) {   
                    han++;   
                }   
                total = len.length + han;   
            }   
            if (total <= 10) {   
                $("#tip").html(total);   
            } else {   
                $("#tip").html("最多10个字符").css({   
                    color: "#f40"  
                });   
            }   
        })   
    })  
JS

收集转载自:http://***

转载于:https://www.cnblogs.com/JoannaQ/p/3281699.html

猜你喜欢

转载自blog.csdn.net/weixin_33937778/article/details/94153359