Yau*_*n.F 12 javascript jquery
我试图在TEXT区域控件上重现标准的即时消息行为:输入作为发送按钮.ctrl +输入为真实输入.
$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e)
{
if (!e.ctrlKey && e.keyCode == 13)
{
SendMessage();
return false;
}
else if(e.keyCode == 13)
{
$(this).val($(this).val() + "\n");
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我已尝试使用注释行和不使用.不行.简单的输入按预期工作.任何想法如何在ctrl + enter上添加回车?
关键代码没问题.它们被正确检测到.所以如果按预期工作的话.但添加新行的工作不正确(在FF中,Chrome可正常工作).所以我需要正确的多浏览器方式将新行符号插入textarea.如果没有手动添加字符串(通过基于ctrl + enter的某些事件),它会更好.
更改按键事件无效."\ r \n"没有帮助.
测试页面位于此处
Tim*_*own 18
以下内容适用于所有主流浏览器,包括IE.当你按下ctrl-enter时,它的行为就像按下回车键一样:
function MessageTextOnKeyEnter(e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
var val = this.value;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
this.focus();
var range = document.selection.createRange();
range.text = "\r\n";
range.collapse(false);
range.select();
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
一些潜在的原因:
在引用函数之前先定义该函数。
确保在事件中绑定事件document.ready,以便在引用 dom 项时存在它。
改成。else (e.keyCode == 13)else if (e.keyCode == 13)
确保这是 a textarea,而不是 an input[type=text]。
考虑使用keypress而不是keydown.
有些浏览器会在使用 ctrl 修饰键keyCode == 10时而不是发送keyCode == 13(有些浏览器即使您不使用 ctrl 修饰键也会发送)。
| 归档时间: |
|
| 查看次数: |
16886 次 |
| 最近记录: |