当我使用HTML5 button
时,空格键在contenteditable
元素中不起作用。但它在div
元素的完美工作。我怎样才能让它运转起来?有人能帮我吗?
请在这里查看:https://jsfiddle.net/Issact/f6jc5th4/
HTML:
<div contenteditable="true">
This is editable and the spacebar does work in "Div" for the white-space
</div>
<button contenteditable="true">
This is editable and the spacebar does not work in "button" for the white-space
</button>
CSS:
div {
background-color:black;
padding:20px;
color:#fff;
}
button {
background-color:green;
padding:20px;
color:#fff;
}
用这个
<button
contenteditable="true"
onclick="if (!event.x && !event.y && !event.clientX && !event.clientY) {event.preventDefault(); insertHtmlAtCursor(' ');} else { }"> This is editable and the spacebar does not work in "button" for the white-space </button>
<script type="text/javascript">
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
window.getSelection().collapseToEnd();
window.getSelection().modify('move', 'forward', 'character');
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
document.selection.collapseToEnd();
document.selection.modify('move', 'forward', 'character');
}
}
</script>
在这里添加了现场演示https://jsfiddle.net/jalayoza/f6jc5th4/3/
希望这可以帮助
将文本包装在按钮标记内,并使用跨度使其成为可信的范围
HTML
<div contenteditable="true">
This is editable and the spacebar does work in "Div" for the white-space
</div>
<button >
<span contenteditable="true">
This is editable and the spacebar does not work in "button" for the white-space
</span>
</button>
CSS
div {
background-color:black;
padding:20px;
color:#fff;
}
button {
background-color:green;
padding:20px;
color:#fff;
}
希望这有效
您需要创建一个事件侦听器,在单击空格键时阻止默认事件,然后使用execCommands以编程方式输入。
MDN链接:https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
@ Jalay的答案几乎有效,但并不完全。这对我有用:
注释掉window.getSelection()。collapseToEnd(); Jalay功能的一部分:
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
//window.getSelection().collapseToEnd();
window.getSelection().modify('move', 'forward', 'character');
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
document.selection.collapseToEnd();
document.selection.modify('move', 'forward', 'character');
}
}
然后侦听空格键keyup事件,并根据需要插入空格:
$(document).on('keyup', 'button', function(e){
if(e.keyCode == 32){
insertHtmlAtCursor(' ');
}
});
这也有利于动态添加内容。