Javascript to run a function when input focus

2019-09-03 09:59发布

What is the code to run a function, say called "myfunction" when a user clicks within an input box (focus).

I have seen examples in jquery but I cant see how to do it with straight javascript.

标签: javascript
3条回答
Fickle 薄情
2楼-- · 2019-09-03 10:59
var addEvent = (function(){
  /// addEventListener works for all modern browsers
  if ( window.addEventListener ) {
    /// I'm returning a closure after the choice on which method to use
    /// has been made, so as not to waste time doing it for each event added.
    return function(elm, eventName, listener, useCapture){
      return elm.addEventListener(eventName,listener,useCapture||false);
    };
  }
  /// attachEvent works for Internet Explorer
  else if ( window.attachEvent ) {
    return function(elm, eventName, listener){
      /// IE expects the eventName to be onclick, onfocus, onkeydown (and so on)
      /// rather than just click, focus, keydown as the other browsers do.
      return elm.attachEvent('on'+eventName,listener);
    };
  }
})();

Using the above cross browser function you can then do the following (once the dom is fully loaded):

addEvent(document.getElementById('your_input'),'focus',function(e){
  var input = e.target || e.srcElement;
  alert('this input has gained focus!');
});
查看更多
Anthone
3楼-- · 2019-09-03 11:02

use the onfocus attribute

<input type="text" onfocus="someFunc()">

<script>
  function someFunc(){

  }
</script>
查看更多
家丑人穷心不美
4楼-- · 2019-09-03 11:05
document.getElementById("elementId").addEventListener("focus",function(e){
 //Do Something here
});
查看更多
登录 后发表回答