使得输入文本字段保持焦点而不是在我点击其他内容时丢失(要始终关注输入id =“input_message”)?

时间:2012-11-26 21:19:31

标签: javascript html css

我在一个文本字段(输入消息)和发送按钮上方进行了简单的网络聊天,bubles(消息)。如何使输入文本字段保持焦点而不是在我点击其他东西时丢失(要始终关注输入id =“input_message”)?

3 个答案:

答案 0 :(得分:10)

var el = document.getElementById('input_message');

el.focus();

el.onblur = function () {
    setTimeout(function () {
        el.focus();
    });
};

这是小提琴:http://jsfiddle.net/MwaNM/

答案 1 :(得分:5)

这是一个肮脏的黑客。

<input type="text" id="input_message" />
<script type="text/javascript">
    with (document.getElementById('input_message')) {
        onblur = function(e) {
            var elm = e.target;
            setTimeout(function(){elm.focus()});
        }
        onkeydown = function(e) {
            var key = e.which || e.keyCode;
            if (key == 9) e.preventDefault();
            // code for tab is 9
        }
    }
</script>

答案 2 :(得分:0)

var obj = { Id: "100", Name: "John", 
            Address:  [{ Id:1, Name:"Bangalore" }, { Id:2, Name: "Mysore" } ] };

function GetPropertyValue(object, dataToRetrieve) {
    dataToRetrieve.split('.').forEach(function(token) {
      if (object) object = object[token];
    });
    
    return object;
}

console.log(
  GetPropertyValue(obj, "Address.0.Name"),
  GetPropertyValue(obj, "Address.1.Id"),
  GetPropertyValue(obj, "Name"),
  GetPropertyValue(obj, "Id"),
  GetPropertyValue(obj, "Unknown"),
  GetPropertyValue(obj, "Some.Unknown.Property")
);

http://jsfiddle.net/653w1mpv/