制作< br>而不是< div>< / div>在contenteditable上按Enter键 [英] Make a <br> instead of <div></div> by pressing Enter on a contenteditable
问题描述
我在我的键盘事件处理程序中写了一些代码来插入< br>
来响应按下Enter键:
I've written a bit of code in my keyboard event handler to insert a <br>
in response to the press of the Enter key:
event.preventDefault();
document.execCommand('InsertHTML', true, '<br>');
这只适用于光标在两个字母之间的情况,如果它最后我需要两个<峰; br>
-elements。我可以检测到我是否在一条线的尽头?还是输入问题的其他一些工作想法?
This only works if the cursor is between two Letters, if its on the end i need two <br>
-Elements. Can i detect if i'm on the end of a Line? Or some other working idea for the Enter problem?
我还尝试捕捉正常的键事件(按下按下的ctrl-Key)并创建一个键盘事件JS,其中Enter键与ctrl一起按下。但这不起作用......
I also tried to catch the normal key-event (wothout the ctrl-Key pressed) and create a keyboard-event with JS where the Enter Key is pressed together with the ctrl. But this dosn't work…
它只需要在Webkit / Safari中工作......
It only has to Work in Webkit/Safari…
推荐答案
为了解决您的问题,请始终将 br 元素作为您的contenteditable div的最后一个元素。这将确保注入br元素时的可预测行为与注入div元素的浏览器默认值。您可以在keyup和mouseup上检查 lastChild 以确保它是br元素。假设你有一个类似的文件:
In order to solve your problem, always keep a br element as the last element of your contenteditable div. This will ensure predictable behavior when injecting a br element vs. the browser default of injecting div elements. You can check the lastChild on keyup and mouseup to make sure it's a br element. Assuming you have a document like:
<div id="editable" contenteditable="true"></div>
您可以使用以下JavaScript(w / jQuery 1.4+)将br元素保留为最后一个元素并注入br元素而不是div div:
You can use the following JavaScript (w/ jQuery 1.4+) to keep a br element as the last element and inject a br element instead of div div:
$(function(){
$("#editable")
// make sure br is always the lastChild of contenteditable
.live("keyup mouseup", function(){
if (!this.lastChild || this.lastChild.nodeName.toLowerCase() != "br") {
this.appendChild(document.createChild("br"));
}
})
// use br instead of div div
.live("keypress", function(e){
if (e.which == 13) {
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
}
});
});
测试Apple OS X w / Google Chrome 7,Mozilla Firefox 3.6,Apple Safari 5)。尝试使用 ierange 以使其在Windows Internet Explorer中正常工作。
Tested on Apple OS X w/ Google Chrome 7, Mozilla Firefox 3.6, Apple Safari 5). Try using ierange to get this to work in Windows Internet Explorer.
这篇关于制作< br>而不是< div>< / div>在contenteditable上按Enter键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!