简体   繁体   English

专注于输入字段

[英]Fix focus on input field

Is there a way to fix a focus on input field until, say, user enters 4 characters? 在用户输入4个字符之前,是否有办法将焦点固定在输入字段上? The reason I need it is because i don't have a background for my text area (stylistic purpose) and if user clicks on a random place on my page it will be hard for many users to locate the text area. 我需要它的原因是因为我的文本区域没有背景(出于样式目的),并且如果用户单击页面上的随机位置,许多用户将很难找到该文本区域。

Here is my text field and button 这是我的文本字段和按钮

<div id="inputtext">
      <input type="text" id="dreamtext" autofocus/>
      <input type="submit" id="nextstepbutton" value="next step" onclick="window.open('step3.html','_self','resizable=yes')" />
    </div>

I already have some scripts going on which hides the button and changes some div when there are less then 4 characters in text field. 我已经有了一些脚本,当文本字段中的字符数少于4个时,这些脚本将隐藏按钮并更改一些div。 It would be super great if I could also implement permanent focus in this script. 如果我还可以在此脚本中实现永久关注,那就太好了。

$(function(){
     $("#nextstepbutton").hide();

     $("#dreamtext").keyup(function() {
         var val = $(this).val();
         if (val.length > 3) {
             $('#nextstepbutton').show();
             document.getElementById("message").innerHTML = "<h1>press 'enter' key or next step</h1>";
         }
         else {
             $('#nextstepbutton').hide();
             document.getElementById("message").innerHTML = "<h1>type please</h1>";
         }

     });
});

Thanks. 谢谢。

document.getElementById('dreamtext').addEventListener('blur', function() {
    this.value.length > 3 || this.focus(); 
});

Use the blur event. 使用模糊事件。 It triggers when focus is lost. 失去焦点时触发。

use blur() , the opposite of focus() ... 使用blur() ,与focus()相反...

$('#dreamtext').on('blur',function(){
   if (this.value.length < 4) this.focus();
});

Demo 演示

Using a event listener you could do something like 使用事件侦听器,您可以执行以下操作

 $('#textbox').change(function(){

    if ( $(this).val().length <= 4 ) {

        $(this).css('border', '1px solid orange');

    } else {

        $(this).css('border', '0');

    }

});

When the user initially clicks the box it'll have a 'orange' border until it has 4 or more characters, indicating it needs attention. 当用户最初单击该框时,它将具有“橙色”边框,直到它具有4个或更多字符为止,表示需要注意。

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

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