【问题标题】:How can I detect when user clicks outside of input box (cursor goes away)?如何检测用户何时在输入框外单击(光标消失)?
【发布时间】:2017-06-28 04:15:18
【问题描述】:

blur 在 Safari 上可以完成这项工作,但在 Firefox 上却会导致问题。似乎当鼠标移到输入框之外时,Firefox 上的模糊会触发,而不是在实际移除光标时(例如当用户单击框外的某个位置时)。这对我来说是个问题,因为我不希望我的代码仅仅因为用户的光标移到框外而触发......我只希望它在用户在框外单击以表明他们完成时触发打字。我什至尝试过事件聚焦,但同样的问题发生了。这是我的代码:

<div class="form-group">
    <label for="min-reward-amount-input">Minimum reward amount</label>
    <div class="input-group">
        <span class="input-group-addon">$</span>
        <input type="number" step="0.1" min="0" class="form-control" id="min-reward-amount-input" placeholder="0.00">
    </div>
</div>


$("#min-reward-amount-input").blur(function(){
    var initialValue = parseFloat($("#min-reward-amount-input").val());
    if(!isNaN(initialValue) && initialValue>=0) {
        var processedValue = initialValue.toFixed(2);
        $("#min-reward-amount-input").val(processedValue);

    } else {
        $("#min-reward-amount-input").val("0.00");
    }
});

【问题讨论】:

  • It seems that blur on Firefox fires when the mouse is moved outside of the input box - Firefox 对我来说不是这样的 - 在你的代码中 jsfiddle.net/wf84tcwd
  • 嗯,很有趣。也许引导程序引起了问题。我在输入中添加了我的代码。
  • 有趣的是,当使用您的 HTML 时,即输入类型是数字,firefox 仍会在正确的时间触发模糊(即当输入失去焦点时) - 但数字不会更新为具有 2 个十进制数字
  • 哇,firefox 数字输入在很多方面都相当“有趣”!
  • 将点击事件处理程序附加到文档。

标签: javascript jquery html css


【解决方案1】:

使用 jQuery,我会使用 eventListeners 做这样的事情:

document.addEventListener("click", function (event) {
    if (event.target.className !== "textBox") {
        window.alert("Clicked outside input field");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST">
<input type="text" name="textBox_1" class="textBox" placeholder="Field 1" />
<input type="text" name="textBox_2" class="textBox" placeholder="Field 2" />
<input type="text" name="textBox_3" class="textBox" placeholder="Field 3" />

<input type="submit" name="submit" class="submit" value="Next" />
</form>

虽然可能有,而且可能是更优雅的解决方案,而不是查看类名。

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2022-07-24
    • 2018-09-12
    • 2019-07-01
    • 1970-01-01
    • 2016-10-25
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多