当用户在输入框(焦点)中单击时,运行函数的代码是什么,比如称为“myfunction”。
我在jquery中看到了一些例子,但是我不知道如何用直接的javascript做到这一点。
答案 0 :(得分:3)
使用onfocus属性
<input type="text" onfocus="someFunc()">
<script>
function someFunc(){
}
</script>
答案 1 :(得分: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!');
});
答案 2 :(得分:1)
document.getElementById("elementId").addEventListener("focus",function(e){
//Do Something here
});