JQuery 实现开发常用功能

jQuery
378
0
0
2023-02-12

标签克隆的两种实现方式:

<body>
    <div>
        <p>
            <a onclick="Add(this)">+</a>
            <input type="text"/>
        </p>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
        function Add(ths) {
            var p = $(ths).parent().clone();
            p.find('a').text('-');
            p.find('a').attr('onclick','Remove(this)');
            $(ths).parent().parent().append(p);
        }
        function Remove(ths) {
            $(ths).parent().remove();
        }
    </script>
</body>
<head>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
        function add(self){
          // 注意:if var $clone_obj=$(".outer .item").clone();会一遍二,二变四的增加
          var $clone_obj=$(self).parent().clone();
           $clone_obj.children(":button").val("-").attr("onclick","removed(this)");
           $(self).parent().parent().append($clone_obj);
        }
       function removed(self){
           $(self).parent().remove()
       }
    </script>

<body>
      <div class="outer">
          <div class="item">
                  <input type="button" value="+" onclick="add(this);">
                  <input type="text">
          </div>
      </div>
</body>

实现记住密码:

<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
        var strName = localStorage.getItem('keyName');
        var strPass = localStorage.getItem('keyPass');
        if(strName){
            $('#user').val(strName);
        }if(strPass){
            $('#pass').val(strPass);
        }
        if(strName!=null && strPass!=null)
            $('#remember').attr("checked",true);
    });
    function login_click(){
            var strName = $('#user').val();
            var strPass = $('#pass').val();
            if($('#remember').is(':checked')){
                localStorage.setItem('keyName',strName);
                localStorage.setItem('keyPass',strPass);
            }else{
                localStorage.removeItem('keyName',strName);
                localStorage.removeItem('keyPass');
            }
            window.location.reload();
        }
</script>

<body>
    <form action="/" method="post" onsubmit="return login_click();">
        账号: <input type="text" id="user" placeholder="用户名" name="username" /><br><br>
        密码: <input type="password" id="pass" placeholder="密码" name="password" /><br><br>
        记住密码: <input type="checkbox" id="remember">
        <input type="submit" value="用户登录"/>
    </form>
</body>

全选全不选与反选:

<head>
     <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<script type="text/javascript">
        function CheckAll(){
            $('tbody input[type="checkbox"]').prop('checked',true);
        }
        function CancleAll(){
            $('tbody input[type="checkbox"]').prop('checked',false);
        }
        function ReverseAll() {
            $('tbody input[type="checkbox"]').each(function () {
                if($(this).prop('checked')){
                    $(this).prop('checked',false);
                }else{
                    $(this).prop('checked',true);
                 }
             });
        }
</script>
<body>
<table id="tab" border="1" cellspacing="0">
    <thead>
        <tr>
            <th>选择</th><th>用户ID</th><th>用户名称</th><th>用户邮箱</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1001</td>
            <td name="user"> lyshark</td>
            <td name="email"> lyshark@123.com</td>
        </tr>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1002</td>
            <td name="user"> admin</td>
            <td name="email"> admin@123.com</td>
        </tr>
    </tbody>
</table>
    <input type="button" id="but1" value="全选" onclick="CheckAll()" />
    <input type="button" id="but1" value="全不选" onclick="CancleAll()" />
    <input type="button" id="but1" value="反选" onclick="ReverseAll()" />
</body>

提取选中表格指定字段: 选择框表单,通过选择不同表格读取表格中的数据.

<head>
     <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<script type="text/javascript">
    $(document).ready(function(){
      $("#but1").click(function(){
            var obj = $("#tab");          // 定位到table表格
            // 在table中找input下类型为checkbox属性为选中状态的数据
            var check = $("table input[type=checkbox]:checked");
            check.each(function(){        // 遍历节点
                var row = $(this).parent("td").parent("tr");  // 获取选中行
                var id = row.find("[name='uid']").html();     // 取出第一行的属性
                var name = row.find("[name='user']").html();
                alert("选中行的ID: " + id + "名字: " + name)
            });
      });
    });
</script>
<body>
<table id="tab" border="1" cellspacing="0">
    <thead>
        <tr>
            <th>选择</th><th>用户ID</th><th>用户名称</th><th>用户邮箱</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1001</td>
            <td name="user"> lyshark</td>
            <td name="email"> lyshark@123.com</td>
        </tr>
        <tr>
            <td> <input type="checkbox"></td>
            <td name="uid"> 1002</td>
            <td name="user"> admin</td>
            <td name="email"> admin@123.com</td>
        </tr>
    </tbody>
</table>
    <input type="button" id="but1" value="选择" onclick="check()" />
</body>

返回顶部的实现方式:

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script>
  window.onscroll=function(){
  var current=$(window).scrollTop();
  console.log(current)
    if (current>100)
    {
      $(".returnTop").removeClass("hide")
    }
    else {
      $(".returnTop").addClass("hide")
    }
  }
   function returnTop(){
       $(window).scrollTop(0)
   }
</script>
<style>
    .returnTop{
        height: 60px;
        width: 100px;
        background-color: darkgray;
        position: fixed;
        right: 0;
        bottom: 0;
        color: greenyellow;
        line-height: 60px;
        text-align: center;
    }
    .hide{
    display: none;
    }
</style>
</head>
<body>
     <p>hello</p>
     <p>hello</p>
     <p>hello</p>
     <p>请手动添加更多标签来测试.</p>
     <div class="returnTop hide" onclick="returnTop();">返回顶部</div>
</body>
</html>

二级联动菜单(纵向)的实现:

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <style>
          .menu{
              height: 500px;
              width: 10%;
              background-color: gainsboro;
              float: left;
          }
         .title{
             background-color: #425a66;
           }
         .hide{
             display: none;
         }
    </style>
</head>
<body>
<div class="outer">
    <div class="menu">
        <div class="item">
            <div class="title">菜单一</div>
            <div class="con">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单二</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
        <div class="item">
            <div class="title">菜单三</div>
            <div class="con hide">
                <div>111</div>
                <div>111</div>
                <div>111</div>
            </div>
        </div>
    </div>
</div>
<script>
      $(".item .title").click(function () {
        $(this).next().removeClass("hide")
        $(this).parent().siblings().children(".con").addClass("hide");
           })
</script>
</body>

联动菜单(横向)的实现:

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
           function tab(self){
               var index=$(self).attr("item");
               $("#"+index).removeClass("hide").siblings().addClass("hide");
               $(self).addClass("current").siblings().removeClass("current");
           }
    </script>
    <style>
        .tab_outer{
            margin: 0px auto;
            width: 60%;
        }
        .menu{
            background-color: #cccccc;
            line-height: 40px;
        }
        .menu li{
            display: inline-block;
        }
        .menu a{
            border-right: 1px solid red;
            padding: 11px;
        }
        .content{
            background-color: tan;
            border: 1px solid green;
            height: 300px;
        }
        .hide{
            display: none;
        }
        .current{
            background-color: darkgray;
            color: yellow;
            border-top: solid 2px rebeccapurple;
        }
    </style>
</head>
<body>
      <div class="tab_outer">
          <ul class="menu">
              <li item="c1" class="current" onclick="tab(this);">菜单一</li>
              <li item="c2" onclick="tab(this);">菜单二</li>
              <li item="c3" onclick="tab(this);">菜单三</li>
          </ul>
          <div class="content">
              <div id="c1">内容一</div>
              <div id="c2" class="hide">内容二</div>
              <div id="c3" class="hide">内容三</div>
          </div>
      </div>
</body>

弹出式模态对话框:

<head>
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
    <script>
    function action1(self){
        $(self).parent().siblings().removeClass("hide");
    }
    function action2(self){
        //$(self).parent().parent().children(".models,.shade").addClass("hide")
        $(self).parent().addClass("hide").prev().addClass("hide");
    }
</script>
    <style>
        .back{
            background-color: rebeccapurple;
            height: 2000px;
        }
        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left:0;
            right: 0;
            background-color: coral;
            opacity: 0.4;
        }
        .hide{
            display: none;
        }
        .models{
            position: fixed;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            height: 200px;
            width: 200px;
            background-color: gold;
        }
    </style>
</head>

<body>
    <div class="back">
        <input id="ID1" type="button" value="弹出" onclick="action1(this)">
    </div>
    <div class="shade hide"></div>
    <div class="models hide">
        <input type="text">
        <input id="ID2" type="button" value="取消" onclick="action2(this)">
    </div>
</body>

拖动面板的实现:

<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script>
    $(function(){
        // 页面加载完成之后自动执行
        $('#title').mouseover(function(){
            $(this).css('cursor','move');
        }).mousedown(function(e){
            //console.log($(this).offset());
            var _event = e || window.event;
            // 原始鼠标横纵坐标位置
            var ord_x = _event.clientX;
            var ord_y = _event.clientY;
            var parent_left = $(this).parent().offset().left;
            var parent_top = $(this).parent().offset().top;
            $(this).bind('mousemove', function(e){
                var _new_event = e || window.event;
                var new_x = _new_event.clientX;
                var new_y = _new_event.clientY;
                var x = parent_left + (new_x - ord_x);
                var y = parent_top + (new_y - ord_y);
                $(this).parent().css('left',x+'px');
                $(this).parent().css('top',y+'px');
            })
        }).mouseup(function(){
            $(this).unbind('mousemove');
        });
    })
</script>

<body>
  <div style="border: 1px solid #ddd;width: 600px;position: absolute;">
      <div id="title" style="background-color: black;height: 40px;color: white;">标题</div>
      <div style="height: 300px;">主体内容</div>
  </div>
</body>

显示隐藏与切换按钮:

<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script>
    $(document).ready(function() {
        $("#hide").click(function () {
            $("p").hide(1000);
        });
        $("#show").click(function () {
            $("p").show(1000);
        });

    //用于切换被选元素的 hide() 与 show() 方法。
        $("#toggle").click(function () {
            $("p").toggle();
        });
    })
</script>
</head>
<body>
    <p>hello</p>
    <button id="hide">隐藏</button>
    <button id="show">显示</button>
    <button id="toggle">切换</button>
</body>

页面标签隐藏:

<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<body>
  <button>hide</button>
  <p>helloworld helloworld helloworld</p>
 <script>
   $("button").click(function(){
       $("p").hide(1000,function(){
           alert($(this).html())
       })
   })
    </script>
</body>

图片放大镜的实现:

<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script>
    $(function(){
          $(".small_box").mouseover(function(){
              $(".float").css("display","block");
              $(".big_box").css("display","block")
          });
          $(".small_box").mouseout(function(){
              $(".float").css("display","none");
              $(".big_box").css("display","none")
          });

          $(".small_box").mousemove(function(e){
              var _event=e || window.event;
              var float_width=$(".float").width();
              var float_height=$(".float").height();
              console.log(float_height,float_width);
              var float_height_half=float_height/2;
              var float_width_half=float_width/2;
              console.log(float_height_half,float_width_half);
               var small_box_width=$(".small_box").height();
               var small_box_height=$(".small_box").width();
//  鼠标点距离左边界的长度与float应该与左边界的距离差半个float的width,height同理
              var mouse_left=_event.clientX-float_width_half;
              var mouse_top=_event.clientY-float_height_half;

              if(mouse_left<0){
                  mouse_left=0
              }else if (mouse_left>small_box_width-float_width){
                  mouse_left=small_box_width-float_width
              }
              if(mouse_top<0){
                  mouse_top=0
              }else if (mouse_top>small_box_height-float_height){
                  mouse_top=small_box_height-float_height
              }
               $(".float").css("left",mouse_left+"px");
               $(".float").css("top",mouse_top+"px")

               var percentX=($(".big_box img").width()-$(".big_box").width())/ (small_box_width-float_width);
               var percentY=($(".big_box img").height()-$(".big_box").height())/(small_box_height-float_height);
                console.log(percentX,percentY)

               $(".big_box img").css("left", -percentX*mouse_left+"px")
               $(".big_box img").css("top", -percentY*mouse_top+"px")
          })
    })
</script>

<style>
    *{
        margin: 0;
        padding:0;
    }
    .outer{
        height: 350px;
        width: 350px;
        border: dashed 5px cornflowerblue;
    }
    .outer .small_box{
        position: relative;
    }
    .outer .small_box .float{
        height: 175px;
        width: 175px;
        background-color: darkgray;
        opacity: 0.4;
        fill-opacity: 0.4;
        position: absolute;
        display: none;
    }
    .outer .big_box{
        height: 400px;
        width: 400px;
        overflow: hidden;
        position:absolute;
        left: 360px;
        top: 0px;
        z-index: 1;
        border: 5px solid rebeccapurple;
        display: none;
    }
    .outer .big_box img{
        position: absolute;
        z-index: 5;
    }
</style>
</head>
<body>
    <div class="outer">
        <div class="small_box">
            <div class="float"></div>
            <img src="small.jpg">
        </div>
        <div class="big_box">
            <img src="big.jpg">
        </div>
    </div>
</body>

JQuery操作表格的各种办法:

<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
  <style type="text/css">
    .on {background-color:#ddd}
  </style>
</head>
<body style="text-align:center"><div class="m-1"></div>
  <h3>jquery操作table的各种方法</h3><div class="m-2"></div>
<table id="aijquery" border="1" cellpadding="7" cellspacing="0" align="center">
    <tr><td>测试1.1</td><td>测试1.2</td><td>测试1.3</td><td>测试1.4</td><td>测试1.5</td><td>测试1.6</td></tr>
    <tr><td>测试2.1</td><td>测试2.2</td><td>测试2.3</td><td>测试2.4</td><td>测试2.5</td><td>测试2.6</td></tr>
    <tr><td>测试3.1</td><td>测试3.2</td><td>测试3.3</td><td>测试3.4</td><td>测试3.5</td><td>测试3.6</td></tr>
    <tr><td>测试4.1</td><td>测试4.2</td><td>测试4.3</td><td>测试4.4</td><td>测试4.5</td><td>测试4.6</td></tr>
    <tr><td>测试5.1</td><td>测试5.2</td><td>测试5.3</td><td>测试5.4</td><td>测试5.5</td><td>测试5.6</td></tr>
</table><div class="m-2"></div>
  <button id="huanse">鼠标经过时换色</button> <button id="jiou">奇偶行不同颜色</button> <button id="addtr">插入一行</button> <button id="addtd">插入一列</button><div class="m-1"></div>
  <button id="hidetr">隐藏/显示第三行</button>
  <button id="hidetd">隐藏/显示第三列</button>
  <div class="m-1"></div>
  <button id="deltr">删除第四行</button>
  <button id="deltd">删除第五列</button>
  <button id="deltrt">删除第二行外所有行</button>
  <button id="deltrd">删除第2到第4行</button>
  <div class="m-1"></div>
  <button id="deltrs">只留前三行</button>
  <button id="deltrf">只留第二到第四行</button>
  <div class="m-1"></div>
  <button id="readtd">读取第三行第四列的值</button>
  <button id="readtdt">读取第三列所有值</button>
  <button id="readtr">读取第三行所有值</button>
<script language="javascript">
    //鼠标经过换色
    $("#huanse").on("click",function(){
        $("#aijquery tr").hover(function(){$(this).children("td").addClass("on");},function(){$(this).children("td").removeClass("on")});
    });
    //奇偶行不同颜色
    $("#jiou").on("click",function(){
        //偶数行 奇数行的话 odd改为even
        $("#aijquery tr:odd").find("td").css("background-color","#e7ffff");
    });
    //插入一行
    $("#addtr").on("click",function(){
        //在表格的末尾添加一行
        //$("#aijquery").append('<tr><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td></tr>');
        //在表格的开头添加一行
        //$("#aijquery").prepend('<tr><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td></tr>');
         //在表格的第二行后面插入一行
          $("#aijquery tr").eq(1).after('<tr><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td><td>new</td></tr>');
    });
    //插入一列
    $("#addtd").on("click",function(){
       //在表格的末尾添加一列
       //$("#aijquery tr").append('<td>newTD</td>');
       //在表格的开头添加一列
       //$("#aijquery tr").prepend('<td>newTD</td>');
       //在表格的第二列后添加一列
       $("#aijquery tr td:nth-child(2)").after('<td>newTD</td>');
    });
    //隐藏/显示第三行
    $("#hidetr").on("click",function(){
        $("#aijquery tr").eq(2).toggle();
    });
    //隐藏/显示第三列
    $("#hidetd").on("click",function(){
        //第一种方法
        //$("#aijquery tr td:nth-child(3)").toggle();
        //第二种方法
        $("#aijquery tr").each(function(){
            //$(this).find("td").eq(2).toggle();
            $("td",$(this)).eq(2).toggle();
        });
    });
    //删除第四行
    $("#deltr").on("click",function(){
        $("#aijquery tr").eq(3).remove();
    });
    //删除第五列
    $("#deltd").on("click",function(){
        $("#aijquery tr td:nth-child(5)").remove();
    });
    //删除第二行外所有行
    $("#deltrt").on("click",function(){
        $("#aijquery tr:not(:eq(1))").remove();
    });
    //只留前三行
    $("#deltrs").on("click",function(){
        $("#aijquery tr:gt(2)").remove();
    });
    //删除第2到第4行
    $("#deltrd").on("click",function(){
        $("#aijquery tr").slice(1,4).remove();
    });
    //只留第二到第四行
    $("#deltrf").on("click",function(){
        $("#aijquery tr").not($("#aijquery tr").slice(1,4)).remove();
    });
    //读取第三行第四列的值
    $("#readtd").on("click",function(){
        var v=$("#aijquery tr:eq(2) td:eq(3)").html();
          alert(v);
    });
    //读取第三列所有值
    $("#readtdt").on("click",function(){
          var arr=[];
        $("#aijquery tr").each(function(){
            arr.push($(this).find("td").eq(2).html());
        });
          alert(arr.join(","));
    });
    //读取第三行所有值
    $("#readtr").on("click",function(){
          var arr=[];
        $("#aijquery tr:eq(2) td").each(function(){
            arr.push($(this).html());
        });
          alert(arr.join(","));
    });
</script>
</body>
</html>