简体   繁体   English

意外的“聚焦”事件触发

[英]unexpected “focusout” event trigering

I try to show text box (#dimVal), when div(#CanvasArea) is clicked. 单击div(#CanvasArea)时,我尝试显示文本框(#dimVal)。 And I want to make this text box disappear, when it loses its focus. 当文本框失去焦点时,我想使其消失。

    <head>
    <script src="jquery-1.5.1.js" type="text/javascript"></script>
    </head>

    <body>
    <div id = "CanvasArea", style = "width:50%; height:600px; border:2px; border-color:orange; border-style:solid; float:left">
    <h3>Click Me</h3>
    </div>

    <input type="text", id="dimVal", value="111", style="position:absolute; display:none; left:300px; top:300px" />

    <script type="text/javascript">
    onMouseDown = function(e){
        $("#dimVal").show();
        $("#dimVal").focus();
        $("#dimVal").focusout(onLostFocus);
    }

    onLostFocus = function(e){
        $("#dimVal").hide();
        $("#dimVal").unbind("focusout");
    }

    $("#CanvasArea").bind("mousedown", onMouseDown);
    </script>

    </body>

I wonder why "focusout" event fires right after mouseclick? 我不知道为什么在鼠标单击后立即触发“ focusout”事件?

这是因为你的鼠标在CanvasArea你提供焦点时dimVal因此dimVal获得后立即失去焦点。

Change mousedown to click event because before click event mousedown event triggers and then your code is executed which sets the focus onto textbox, after the click event is triggered the focus is lost so the focusout event is triggered. 更改mousedownclick事件因为之前click事件mousedown事件触发,然后执行你的代码将焦点设置到文本框,后click触发事件焦点失去了对focusout事件被触发。 Also make use of anonymous function instead of having global functions. 还应使用匿名函数而不是具有全局函数。 Try this. 尝试这个。

$("#CanvasArea").bind("click", function(e){
    $("#dimVal").focusout(function(e){
        $(this).hide().unbind("focusout");
    }).show().focus();
});

I was not able to get your code to work in its current form, so I rewrote it somewhat using the jQuery mouseup function and the newest version of jQuery: 我无法使您的代码以当前形式运行,因此我使用jQuery mouseup函数和最新版本的jQuery重写了一下代码:

$(document).ready(function() { 
$("#CanvasArea").mouseup(function() {
    $("#dimVal").show();
    $("#dimVal").focus();
    $("#dimVal").focusout(onLostFocus);
});

onLostFocus = function(e){
    $("#dimVal").hide();
    $("#dimVal").unbind("focusout");
}
});

this works as intended, shows up when canvas area is clicked and removes focus when the user clicks off the form. 这将按预期工作,在单击画布区域时显示,并在用户单击表单时移除焦点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM