如果 createElement 函数位于
我使用此函数是为了使用 Safari 和 Chrome 将 contentEditable div 上的断行中的
替换为 New Divs
:
$("#form_description").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;
}
}
});
问题是,当我在
中输入内容并按下“返回”键时,我不希望获得
,这样我就可以继续查看列表...
如果我在 LI
元素?
用我的答案编辑:
好吧,我已经成功做到了,但是如果您对代码有任何评论,欢迎您:
$("#form_description").live("keypress", function(e){
if (e.which == 13) {
node = document.getSelection().anchorNode;
nodeName = node.parentNode.nodeName.toLowerCase();
if ((nodeName != "li") && (nodeName != "blockquote")) {
... etc }
I'm using this function in order to replace <DIV>New Divs</DIV>
with <BR>
in break lines on contentEditable divs using Safari and Chrome:
$("#form_description").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;
}
}
});
The problem is that when I'm typing inside an <UL><LI>Something</LI></UL>
and I press the "return" key, I don't want to get a <BR>
, so I can continue whit the list...
How could I create a condition for that function not to work if I'm inside a LI
element?
EDIT WITH MY ANSWER:
Ok, I've managed to do it, but If you have any comment on the code, you're welcome:
$("#form_description").live("keypress", function(e){
if (e.which == 13) {
node = document.getSelection().anchorNode;
nodeName = node.parentNode.nodeName.toLowerCase();
if ((nodeName != "li") && (nodeName != "blockquote")) {
... etc }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,使用
keyup
作为事件名称,keypress仅适用于Firefox。其次,e.这并不总是可用的。主要使用 e.keyCode,然后回退到 e.which:
第三,如果您需要取消按键中触发的默认事件,您可能需要在事件处理程序例程中添加一个 PreventDefault() 。确保它是第一行。
First, use
keyup
as the event name, keypress works only on Firefox.Second, e.which is not always available. Use e.keyCode primarily, and fall back to e.which:
Third, if you need to cancel default events fired in the key-press, you might want to throw in a preventDefault() inside your event handler routine. Make sure it's the first line.