JS類比鍵盤事件 -- 原理及小例子

來源:互聯網
上載者:User

標籤:style   blog   color   使用   io   for   

小例子:

(Chrome下可用,其他瀏覽器未測試,使用新方法,暫不考慮相容性)

 代碼如下:
 1 <input type="button" tabindex="-1" value="點點點點點" id="btn"> 2 <input type="text" placeholder="1"> 3 <input type="text" placeholder="2"> 4 <input type="text" placeholder="3"> 5 <input type="text" placeholder="4"> 6 <input type="text" placeholder="5"> 7 <input type="text" placeholder="6"> 8 <script> 9 var nowEle=document;10 var inputs=[].slice.call(document.querySelectorAll("[type=text]"));11 inputs.forEach(function(el,i){12     el.onfocus=function(){13         nowEle=this;14     };15     /*el.onblur=function(){16         setTimeout(function() {17             nowEle=document;18         }, 0);19     };*/20 });21 btn.onclick=function(ev){22     // console.log(nowEle);23     var e=document.createEvent("KeyboardEvents");24     e.initKeyboardEvent("keydown",true,true,window,"U+0009"); // tab25     if(nowEle==inputs[inputs.length-1])nowEle=document;26     nowEle.focus && nowEle.focus();27     nowEle.dispatchEvent(e);28     // console.log(e);29 };30 document.onkeydown=function(ev){31     // console.log(ev.keyCode,ev.which,ev);32 };33 document.addEventListener("click",function(ev){34     for (var i = 0; i < inputs.length; i++) {35         if(inputs[i]==ev.target || btn==ev.target)return;36     };37     nowEle=document;38 },false);39 </script>

先點著試試。

   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.