How can I shift-select multiple checkboxes like GMail?

后端 未结 13 1080
野趣味
野趣味 2020-11-30 17:33

In GMail, the user can click on one checkbox in the email list, hold down the Shift key, and select a second checkbox. The JavaScript will then select/unselect the checkboxe

13条回答
  •  甜味超标
    2020-11-30 18:08

    Inspired by the fine answers provided, here's a plain JavaScript version using Array.prototype to coerce nodelists to use array functions, rather than for loops.

    (function () { // encapsulating variables with IIFE
      var lastcheck = null // no checkboxes clicked yet
    
      // get desired checkboxes
      var checkboxes = document.querySelectorAll('div.itemslist input[type=checkbox]')
    
      // loop over checkboxes to add event listener
      Array.prototype.forEach.call(checkboxes, function (cbx, idx) {
        cbx.addEventListener('click', function (evt) {
    
          // test for shift key, not first checkbox, and not same checkbox
          if ( evt.shiftKey && null !== lastcheck && idx !== lastcheck ) {
    
            // get range of checks between last-checkbox and shift-checkbox
            // Math.min/max does our sorting for us
            Array.prototype.slice.call(checkboxes, Math.min(lastcheck, idx), Math.max(lastcheck, idx))
              // and loop over each
              .forEach(function (ccbx) {
                ccbx.checked = true
            })
          }
          lastcheck = idx // set this checkbox as last-checked for later
        })
      })
    }())

提交回复
热议问题