模拟Windows 按住Ctrl和shift多选和取消的功能

近期有很多小伙伴想写Windows系统的按住Ctrl和Shift多选和取消多选的功能,然而我近期也写了一个~分享给大家吧!
不说 了直接上代码
下面展示同样高亮的 代码片.

// An highlighted block
<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .backactive{
      background:#4AA0F9;
    }
    td,th{
      width: 200px;
      text-align: center;
      border: 1px solid #dddddd;
    }
  </style>
</head>
<body>
<table class="table">
  <thead>
  <tr><th>1</th><th>1</th><th>1</th><th>1</th></tr>
  </thead>
  <tbody>
  <tr><td>1</td><td>1</td><td>1</td><td>1</td></tr>
  <tr><td>1</td><td>1</td><td>1</td><td>1</td></tr>
  <tr><td>1</td><td>1</td><td>1</td><td>1</td></tr>
  <tr><td>1</td><td>1</td><td>1</td><td>1</td></tr>
  </tbody>
</table>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
  var tableTr = $(".table tbody").find("tr"); // 首先找到tr
  tableTr.click(function (event) {
    if (event.ctrlKey == 1) { // 按住clrl键可以多选 || 取消多选
      if ($(this).hasClass('backactive')) { // 如果当前行为选中状态。
        $(this).removeClass('backactive');
      } else {
        $(this).addClass('backactive');
      }
    } else if (event.shiftKey == 1) { //按住shift键可以多选 || 取消多选
      tableTr.removeClass("backactive");
      var endIndex; // 作为当shift按住时点击行的下标(index)
      for (var k = 0; k < tableTr.length; k++) {
        if (this == tableTr[k]) {
          endIndex = k;
        }
      }

      var start, end;
      if (sessionStorage.startIndex < endIndex) { //做比较,永远将第一次点击行和最后一次点击行的index,的小值赋值给start,大的赋值给end
        start = sessionStorage.startIndex;
        end = endIndex;
      } else {
        start = endIndex;
        end = sessionStorage.startIndex;
      }

      for (var j = 0; j < tableTr.length; j++) {
        if (j >= start && j <= end) {
          $(tableTr[j]).addClass("backactive");
        } else {
          $(tableTr[j]).removeClass("backactive");
        }
      }
    } else if (event.shiftKey !== 1 && event.ctrlKey !== 1) { //正常点击的时候
      var startIndex;
      for (var i = 0; i < tableTr.length; i++) {
        tableTr[i].style.backgroundColor = '';
        if (this == tableTr[i]) {
          startIndex = i;
          sessionStorage.startIndex = startIndex; //将当前行index保存在session当中
        }
      }
      $(this).addClass('backactive').siblings("tr").removeClass("backactive");
    }
  });
</script>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值