Scrolling inner div on key down and up

前端 未结 5 1934
你的背包
你的背包 2021-02-05 20:37

I have build an autocomplete container which displays the first four results and the rest are hidden and can be seen when scrolling the inner div element which holds all the res

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 20:57

    By using tabIndex="-1" attribute on each of the children of a container, the browser will automatically scroll the container to have the child with the current focus in-view.

    Demo (vanilla javascript):

    var listElm = document.querySelector('ul')
    
    // Mark first list item
    listElm.firstElementChild.focus()
    
    // Event listener
    window.addEventListener('keydown', onKeyDown)
    
    // Event callback
    function onKeyDown(e){
      e.preventDefault()
      
      var selectedElm = document.activeElement,
          goToStart,
          // map actions to event's key
          action = {ArrowUp:"previous", Up:"previous", ArrowDown:"next", Down:"next"}
    
      selectedElm = selectedElm[action[e.key] + "ElementSibling"];
    
      // loop if top/bottom edges reached or "home"/"end" keys clicked
      if( !selectedElm || e.key == 'Home' || e.key == 'End' ){
        goToStart = action[e.key] == "next" || e.key == 'Home'
        selectedElm = listElm.children[goToStart ? 0 : listElm.children.length - 1]
      }
      
      selectedElm.focus()
    }
    ul{ 
      list-style: none; 
      border    : 1px solid silver; 
      max-height: 170px;
      padding   : 0;
      margin    : 0;
      scroll-behavior: smooth; /* nice smooth movement */
      overflow  : hidden;      /* set to hidden by OP's request */
    }
    
    li{ padding:.5em; margin:0; }
    li:focus{ background:LIGHTSALMON; outline:none; }
    • item 1
    • item 2
    • item 3
    • item 4
    • item 5
    • item 6
    • item 7
    • item 8
    • item 9
    • item 10
    • item 11
    • item 12
    • item 13
    • item 14
    • item 15

    To make this list accessible (ARIA) read this

提交回复
热议问题