1

当用户在输入框(焦点)内单击时,运行函数的代码是什么,例如称为“myfunction”。

我已经在 jquery 中看到了示例,但我看不到如何使用直接的 javascript 来做到这一点。

4

3 回答 3

3

使用 onfocus 属性

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

<script>
  function someFunc(){

  }
</script>
于 2012-11-04T00:37:42.000 回答
3
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);
    };
  }
})();

使用上面的跨浏览器功能,您可以执行以下操作(一旦 dom 完全加载):

addEvent(document.getElementById('your_input'),'focus',function(e){
  var input = e.target || e.srcElement;
  alert('this input has gained focus!');
});
于 2012-11-04T00:42:12.907 回答
1
document.getElementById("elementId").addEventListener("focus",function(e){
 //Do Something here
});
于 2012-11-04T00:37:07.107 回答