contenteditable和非按钮元素 [英] contenteditable and non button elements
本文介绍了contenteditable和非按钮元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果使用按钮,我可以轻松地对一个满足选择的exec命令。但是使用任何其他元素失败。
I can easily do execcommand on a contenteditable selection if using a button. However using any other element fails.
为什么这样做以及如何使用div元素使其工作。
Why is this and how can I make it work using a div element.
谢谢。
推荐答案
您可以使用 mousedown
事件保存选择在使用点击
事件中的可编辑元素后,使用元素代替按钮并重新恢复它。
You could save the selection by using the mousedown
event on the element being used instead of a button and restore it again after focussing the editable element in the click
event.
I修改了示例代码: http://jsbin.com/atike/40/edit 。这是代码:
I've modified the example code: http://jsbin.com/atike/40/edit. Here's the code:
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
var ranges = [];
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
ranges.push(sel.getRangeAt(i));
}
return ranges;
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(savedSel) {
if (savedSel) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
for (var i = 0, len = savedSel.length; i < len; ++i) {
sel.addRange(savedSel[i]);
}
} else if (document.selection && savedSel.select) {
savedSel.select();
}
}
}
$(function() {
var savedSel;
$('.bold').mousedown(function () {
savedSel = saveSelection();
});
$('.bold').click(function () {
$('#hello').focus();
if (savedSel) {
restoreSelection(savedSel);
}
document.execCommand("bold", false, null);
});
});
这篇关于contenteditable和非按钮元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文