输入空,并专注于文本区域

on enter empty and focus on textarea

本文关键字:文本 区域 于文本 专注 输入      更新时间:2023-09-26

我需要清空并专注于按下回车键的文本区域。我想我写的代码是对的,但有时textarea是空的,但没有焦点有时有焦点,但没有运气清空这个对象。我用了很多不同的代码,但都没有运气。

这是我的js:

<script>
$(document).ready(function() {
    $("#data").focus(function() {
    $(this).empty();
    $(this).focus();
    });
})

    // when the client hits ENTER on their keyboard
    $('#data').keypress(function(e) {

    $this = $(this);
    if($this.val().length == 1)
    {
        var x =  new RegExp("['x00-'x80]+"); // is ascii
        var isAscii = x.test($this.val());
        if(isAscii)
        {
           $("#data").css({"direction": "ltr", "text-align": "left"});
        } else {
            $("#data").css({"direction": "rtl", "text-align": "right"});
        }
    }

        if (e.shiftKey && e.keyCode == 13) {
            $(this).val($(this).val() + "'n");
            return;
          }
            if(e.which == 13) {
                if($this.val().length == 0){
                    alert('your value is empty')
                }
                var now = time();
                if(now+0.5 > counter){
                counter = now;
                $(this).blur();
                $('#datasend').focus().click();
            }else{
            }
            }
        });
    });
这是我的HTML部分:
    <div class="wrap">
    <div class="rooms">
    <div class="clear"></div>
        <div class="roomsicon">
chatrooms
        </div>
        <ul id="rooms">
        </ul>
    </div>
    <div class="chat_box_container">
    <div class="chat_box" id="mydiv">
    <div id="conversation"></div>
    </div>
    <div class="input_field">
        <textarea id="data" placeholder="type your text ... " ></textarea>
        <input type="button" id="datasend" value="send" />
    </div>
    </div>
    <div class="users">
        <div class="usersicon">online users </div>
        <ul id="users">
        </ul>
    </div>
    </div>
    <!-- clear float -->
    <div class="clear"></div>

empty()不删除值

set .val("");

你基本上是在焦点事件中调用焦点导致一个无限循环。不好。

$("#data").focus(function() {
    $(this).val('');
});

为什么你要重新发明HTML5占位符属性,你已经在元素上?

代码中没有id为"data"的元素。另外,当焦点不在元素内部时,您将keypress绑定在#data-element上,当然不会触发。尝试将事件绑定到文档而不是文本区。

有一个autofocus html5标签(布尔值,不需要值),将自动把焦点放在任何输入/文本区域设置:http://www.html5tutorial.info/html5-autofocus.php

这里有很棒的js回退代码:http://sampsonblog.com/tag/html5

想象一下,如果js可用,跨浏览器兼容的表单输入自动聚焦,如果js不可用,启用HTML5的浏览器仍然显示自动聚焦。现在你唯一缺少的是"按下一个键"来自动对焦,如果你确实需要这个功能,所以你需要使用回车键触发上面的代码,似乎更优雅的只是执行自动对焦,虽然我知道它惹恼了残疾用户不能控制他们的光标在页面上的位置,所以从这个角度来看,一个键执行可能会更好。但是有一种方法可以在他们的终端上禁用自动聚焦属性,如果它使残疾用户难以导航,所以不用太担心。

accesskey属性正在讨论中html5,它被删除,但再次采取,这将是最好的方式使用一个键给焦点的表单元素,但正如我所说,它正在讨论中,可以再次删除:http://lists.w3.org/Archives/Public/public-html-a11y/2010Jul/0103.html