2017-09-13 68 views
1

當我選擇一個選項時,如何禁用滾動到所選項目的頂部?這是簡單的多選擇與js,可以使用多選擇沒有clrt + C,代碼下來。當選擇更改時阻止多個選擇滾動到頂部

window.onmousedown = function (e) { 

    var el = e.target; 

    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) { 

     e.preventDefault(); 

     // toggle selection 
     if (el.hasAttribute('selected')) 
      el.removeAttribute('selected'); 
     else 
      el.setAttribute('selected', ''); 

     // hack to correct buggy behavior 
     var select = el.parentNode.cloneNode(true); 
     el.parentNode.parentNode.replaceChild(select, el.parentNode); 
    } 
} 

回答

0

您可以保存先前的scrollTop的位置,並重新塗抹,像這樣:

window.onmousedown = function (e) { 
    var el = e.target; 

    if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) { 

     e.preventDefault(); 

     // save scroll state 
     var yeOldeScroll = el.scrollTop; 

     // toggle selection 
     if (el.hasAttribute('selected')) { 
      el.removeAttribute('selected'); 
     } else { 
      el.setAttribute('selected', ''); 
     } 

     // re-apply scroll state 
     el.scrollTop = yeOldeScroll; 

     // hack to correct buggy behavior 
     var select = el.parentNode.cloneNode(true); 
     el.parentNode.parentNode.replaceChild(select, el.parentNode); 
    } 
} 
相關問題