簡體   English   中英

在上輸入空並專注於textarea

[英]on enter empty and focus on textarea

我需要清空並專注於輸入了keypress的按鍵上的textarea。我認為我寫了正確的代碼,但有時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()不會刪除該值。

設置.val("");

基本上,通過在焦點事件內調用焦點會導致無限循環。 不好。

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

另外,為什么要重新創建元素上已有的HTML5占位符屬性?

您的代碼中沒有ID為“ data”的元素。 另外,當焦點不在元素內時,您keypress綁定到keypress元素上,該元素當然不會觸發。 嘗試將事件綁定到文檔而不是文本區域。

有一個自動對焦的html5標記(布爾值,不需要任何值),它將自動將焦點放在其設置的任何輸入/文本區域上: http : //www.html5tutorial.info/html5-autofocus.php

此處的大量js后備代碼: http//sampsonblog.com/tag/html5

可以將其想像成js是否可用,與跨瀏覽器兼容的表單輸入自動聚焦,如果js不可用,啟用HTML5的瀏覽器仍顯示自動聚焦。.現在,您唯一缺少的是如果您要自動聚焦,請按“鍵”絕對需要該功能,因此您需要使用Enter鍵觸發上面的代碼,似乎只是執行自動對焦看起來更優雅,盡管我知道它使禁用用戶無法控制其光標在頁面上的位置感到煩惱,因此可以執行鍵從這個角度來看,它是更好的選擇,但是有一種方法可以在其末端禁用自動對焦屬性,如果這會使殘疾用戶難以導航,從而不必擔心太多。

正在針對html5討論accesskey屬性,已將其刪除但再次使用,這將是使用鍵將焦點賦予表單元素的最佳方法,但是正如我所說,正在討論中,可以再次刪除它: http:/ /lists.w3.org/Archives/Public/public-html-a11y/2010Jul/0103.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM