How can I shift-select multiple checkboxes like GMail?

后端 未结 13 1047
野趣味
野趣味 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:07

    I took the jQuery version from @BC. and transformed it into an ES6 version, since the code is actually pretty elegantly solving the problem, in case anyone still stumbles across this...

    function enableGroupSelection( selector ) {
      let lastChecked = null;
      const checkboxes = Array.from( document.querySelectorAll( selector ) );
    
      checkboxes.forEach( checkbox => checkbox.addEventListener( 'click', event => {
        if ( !lastChecked ) {
          lastChecked = checkbox;
    
          return;
        }
    
        if ( event.shiftKey ) {
          const start = checkboxes.indexOf( checkbox );
          const end   = checkboxes.indexOf( lastChecked );
    
          checkboxes
            .slice( Math.min( start, end ), Math.max( start, end ) + 1 )
            .forEach( checkbox => checkbox.checked = lastChecked.checked );
        }
    
        lastChecked = checkbox;
      } ) );
    }
    

提交回复
热议问题