zoukankan      html  css  js  c++  java
  • Jquery实用代码片段(转)

    转载原文:http://www.jq-school.com/Show.aspx?id=23

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

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

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

    1. (function($){
    2. $.fn.checkall = function(options){
    3. var defaults = {chname:"checkname[]", callback:null},
    4. options = $.extend(defaults, options),
    5. $obj = $(this),
    6. $items = $("input[name='"+options.chname+"']"),
    7. checkedItem = 0;
    8. $items.click(function(){
    9. if($items.filter(":checked").length === $items.length){
    10. $obj.attr("checked",true);
    11. }else{
    12. $obj.removeAttr("checked");
    13. }
    14. checkedItem = $items.filter(":checked").length;
    15. if(typeof options.callback === "function") options.callback(checkedItem);
    16. });
    17. return $obj.each(function(){
    18. $(this).click(function(){
    19. if($(this).attr("checked")){
    20. $items.attr("checked",true);
    21. }else{
    22. $items.removeAttr("checked");
    23. }
    24. checkedItem = $items.filter(":checked").length;
    25. if(typeof options.callback === "function") options.callback(checkedItem);
    26. });
    27. });
    28. }
    29. })(jQuery);

    3、滚动条自动滚到顶部方法

    1. $("html,body").animate({scrollTop: 0}, "slow");

    4、滚动条自动滚到底部方法

    1. var s = $("body").height()-$(window).height();
    2. $("html,body").animate({scrollTop: s}, "slow");

    5、jQuery自动根据图片高度宽度缩

    1. jQuery.fn.ImageAutoSize = function(width,height){
    2. $(“img”,this).each(function(){
    3. var image = $(this);
    4. if(image.width()>width){
    5. image.width(width);
    6. image.height(width/image.width()*image.height());
    7. }
    8. if(image.height()>height){
    9. image.height(height);
    10. image.width(height/image.height()*image.width());
    11. }
    12. });
    13. }

    调用:先引用上面的脚本或将上页的脚本放入自己的JS库,然后只要再加 $(function(){ $(“图片组所在的容器”).ImageAutoSize(限制最大宽,限制最大高);});

    6、JQuery IFrame框架高度自适应(支持嵌套–兼容IE,ff,safafi,chrome)

    1. $("#IframeID").load(function() {
    2. $(this).height($(this).contents().height());
    3. })

    有一点需要注意的,我也在调试的时候才发现的,耽误了不少时间。就是绑定事件必须在iframe加载完毕之前绑定,否则不会执行。
    以下是jQuery,load事件的概述
    在每一个匹配元素的load事件中绑定一个处理函数。
    如果绑定给window对象,则会在所有内容加载后触发,包括窗口,框架,对象和图像。如果绑定在元素上,则当元素的内容加载完毕后触发。
    注意:只有当在这个元素完全加载完之前绑定load的处理函数,才会在他加载完后触发。如果之后再绑定就永远不会触发了。所以不要在$(document).ready()里绑定load事件,因为jQuery会在所有DOM加载完成后再绑定load事件。

    ★ 使用jQuery来切换样式表


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

    ★ jQuery检测浏览器类型

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

    ★ jQuery验证某个元素是否为空
    if ($("#Demo").html()) { //null;}
    ★ jQuery从集合中获得索引值
    $("ul > li").click(function () {
    var index = $(this).prevAll().length;
    ★ jQuery选择被选中的option元素
    $("#someElement").find("option:selected");
    ★ jQuery为选择器绑定方法
    $("table").delegate("td", "hover", function(){
    $(this).toggleClass("hover");
    }); //1.42版后,delegate替代live,因为它们提供了更好的上下文支持
    ★ jQuery自动滚动到页面中的某区域(可以看做一个小插件)
    jQuery.fn.Autoscroll = function(sel) {
    $('html,body').animate(
    {scrollTop: $(sel).offset().top},500
    );
    } //调用:$("#area_name").Autoscroll();
    ★ 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);
    ★ jQuery判断某个元素是否可见

    view source

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

    ★ 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();
    ★ jQuery使用.siblings()选择同辈元素
    // 少年,你是否这样操作过
    $('#nav li').click(function(){
    $("#macoArea li").removeClass("current");
    $(this).addClass("current");
    });
    //这样做是不是会更好呢
    $("#nav li").click(function(){
    $(this).addClass("current").siblings().removeClass("current");
    });
    ★ jQuery操作复选框全选反选
    var sta = false; //你懂,全局东东
    $('a').click(function() {
    $("input[type=checkbox]").attr("checked",!sta);
    sta = !sta;
    });
    ★ jQuery获得鼠标光标位置x和y
    $(document).mousemove(function(e)}
    $(document).ready(function() {
    $().mousemove(function(e){
    $("#macoArea").html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
    });
    });
    ★ jQuery解析XML
    function ParseXml(xml) {
    $(xml).find("Node").each(function(){
    $("#macoArea").append($(this).attr("Author") + "");
    );
    }
    ★ jQuery判断图像是否被完全加载进来
    $('#demoImg').attr("src", "demo.jpg").load(function() {
    alert("是的,你看到的是真的");
    });
    ★ jQuery让Cookie过期
    var date = new Date();
    date.setTime(date.getTime() + (x * 60 * 1000));
    $.cookie("example", "foo", { expires: date });
    ★ jQuery禁止鼠标右键
    $(function(){
    $(document).bind("contextmenu",function(e){
    return false;
    });
    });

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

    1. $(function() {
    2. if ($.browser.msie && ($.browser.version == "6.0")) {
    3. alert("<img src='browser/IE.png'>This is MS IE " + $.browser.version);
    4. } else if ($.browser.msie && ($.browser.version == "7.0")) {
    5. alert("<img src='browser/IE.png'>This is MS IE " + $.browser.version);
    6. } else if ($.browser.msie && ($.browser.version == "8.0")) {
    7. alert("This is MS IE " + $.browser.version);
    8. } else if ($.browser.msie && ($.browser.version == "9.0")) {
    9. $("#browser").html("This is MS IE " + $.browser.version);
    10. } else if ($.browser.safari) {
    11. $("#browser").html("<This is safari!");
    12. } else if ($.browser.webkit) {
    13. $("#browser").html("This is chrome!");
    14. } else if ($.browser.mozilla) {
    15. $("#browser").html("This is firefox!");
    16. } else if ($.browser.opera) {
    17. $("#browser").html("This is opera");
    18. } else {
    19. $("#browser").html("i don't konw!");
    20. }
    21. })

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

    1. $(function() {
    2. $("#txt").bind("keyup change",
    3. function() {
    4. var len = $(this).val();
    5. var total = 0;
    6. var han = 0;
    7. for (i = 0; i < len.length; i++) {
    8. if (len[i].match(/[^\x00-\xff]/ig) != null) {
    9. han++;
    10. }
    11. total = len.length + han;
    12. }
    13. if (total <= 10) {
    14. $("#tip").html(total);
    15. } else {
    16. $("#tip").html("最多10个字符").css({
    17. color: "#f40"
    18. });
    19. }
    20. })
    21. })

    jquery实现复选框全选、全不选和反选

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>全选,不全选,反选</title>
    <script src="http://www.jq-school.com/js/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
    $(function () {
    $("#selectAll").click(function () {//全选
    $("#playList :checkbox").attr("checked", true);
    });

    $("#unSelect").click(function () {//全不选
    $("#playList :checkbox").attr("checked", false);
    });

    $("#reverse").click(function () {//反选
    $("#playList :checkbox").each(function () {
    $(this).attr("checked", !$(this).attr("checked"));
    });
    });
    });
    </script>
    </head>
    <body>
    <div id="playList">
    <input type="checkbox" value="歌曲1" />歌曲1<br />
    <input type="checkbox" value="歌曲2" />歌曲2<br />
    <input type="checkbox" value="歌曲3" />歌曲3<br />
    <input type="checkbox" value="歌曲4" />歌曲4<br />
    <input type="checkbox" value="歌曲5" />歌曲5<br />
    <input type="checkbox" value="歌曲6" />歌曲6
    </div>
    <input type="button" value="全选" id="selectAll" />
    <input type="button" value="全不选" id="unSelect" />
    <input type="button" value="反选" id="reverse" />
    </body>
    </html>

  • 相关阅读:
    C/C++&java communicate with each other 之 video file-streaming
    C/C++&java communicate with each other 之 video snapshot
    protobuf io 代码阅读
    利用逆波兰表达式,二叉树对sql语句解析
    cocos2d-x 添加sqlite3 时 报 lua_Number 错误
    error LNK2019: 无法解析的外部符号 _acosh,该符号在函数 _acoshFunc 中被引用
    visual studio 运行程序在副显示器上
    lua table 中#,getn,maxn 的区别
    'Cordova/CDVViewController.h' file not found
    [ISSUE]cannot run on the selected destination
  • 原文地址:https://www.cnblogs.com/dwfbenben/p/2868282.html
Copyright © 2011-2022 走看看