Javascript contenteditable,在文本末尾设置插入符号(跨浏览器)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4233265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
contenteditable, set caret at the end of the text (cross-browser)
提问by Tim Down
output in Chrome:
Chrome 中的输出:
<div id="content" contenteditable="true" style="border:1px solid #000;width:500px;height:40px;">
hey
<div>what's up?</div>
<div>
<button id="insert_caret"></button>
I believe in FFit would look something like this:
我相信FF它看起来像这样:
hey
<br />
what's up?
and in IE:
在IE 中:
hey
<p>what's up?</p>
unfortunately, there is no nice way of making it so that every browser inserts a <br />
instead of a div- or p-tag, or at least I couldn't find anything online.
不幸的是,没有好的方法可以让每个浏览器插入一个<br />
而不是 div 或 p 标签,或者至少我在网上找不到任何东西。
ANYWAY, what I am trying to do now is, when I hit the button, I want the caret to be set at the end of the text, so it should look something like this:
无论如何,我现在想要做的是,当我点击按钮时,我希望将插入符号设置在文本的末尾,所以它应该是这样的:
hey
what's up?|
any way to do this so it works in all browser?
有什么方法可以做到这一点,使其适用于所有浏览器?
example:
例子:
$(document).ready(function()
{
$('#insert_caret').click(function()
{
var ele = $('#content');
var length = ele.html().length;
ele.focus();
//set caret -> end pos
}
}
回答by Tim Down
The following function will do it in all major browsers:
以下函数将在所有主要浏览器中执行此操作:
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
placeCaretAtEnd( document.querySelector('p') );
p{ padding:.5em; border:1px solid black; }
<p contentEditable>foo bar </p>
Placing the caret at the start is almost identical: it just requires changing the Boolean passed into the calls to collapse()
. Here's an example that creates functions for placing the caret at the start and at the end:
将插入符号放在开头几乎是相同的:它只需要更改传递到collapse()
. 下面是一个创建用于将插入符号放置在开头和结尾的函数的示例:
function createCaretPlacer(atStart) {
return function(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(atStart);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(atStart);
textRange.select();
}
};
}
var placeCaretAtStart = createCaretPlacer(true);
var placeCaretAtEnd = createCaretPlacer(false);
回答by dimid
Unfortunately Tim's excellent answer worked for me only for placing at the end, for placing at the start I had to modify it slightly.
不幸的是,Tim 的出色答案仅适用于最后放置,对于放置在开始时我不得不稍微修改它。
function setCaret(target, isStart) {
const range = document.createRange();
const sel = window.getSelection();
if (isStart){
const newText = document.createTextNode('');
target.appendChild(newText);
range.setStart(target.childNodes[0], 0);
}
else {
range.selectNodeContents(target);
}
range.collapse(isStart);
sel.removeAllRanges();
sel.addRange(range);
target.focus();
target.select();
}
Not sure though if focus()
and select()
are actually needed.
不知道但如果focus()
和select()
实际需要。
回答by vsync
This (live) example shows a short simple function, setCaretAtStartEnd
, which takes two arguments; A (editable) node to place the caret at & a Boolean indicating where to place it (start or end of the node)
这个(实时)示例显示了一个简短的简单函数setCaretAtStartEnd
,它接受两个参数;一个(可编辑的)节点来放置插入符号 & 一个布尔值,指示放置它的位置(节点的开始或结束)
const editableElm = document.querySelector('[contenteditable]');
document.querySelectorAll('button').forEach((elm, idx) =>
elm.addEventListener('click', () => {
editableElm.focus()
setCaretAtStartEnd(editableElm, idx)
})
)
function setCaretAtStartEnd( node, atEnd ){
const sel = document.getSelection();
node = node.firstChild;
if( sel.rangeCount ){
['Start', 'End'].forEach(pos =>
sel.getRangeAt(0)["set" + pos](node, atEnd ? node.length : 0)
)
}
}
[contenteditable]{ padding:5px; border:1px solid; }
<h1 contenteditable>Place the caret anywhere</h1>
<br>
<button>Move caret to start</button>
<button>Move caret to end</button>
回答by Matt W-D
If you are using the google closure compiler, you can do the following (somewhat simplified from Tim's answer):
如果您使用的是 google 闭包编译器,则可以执行以下操作(从 Tim 的回答中略有简化):
function placeCaretAtEnd(el) {
el.focus();
range = goog.dom.Range.createFromNodeContents(el);
range.collapse(false);
range.select();
}
Here's the same thing in ClojureScript:
这是 ClojureScript 中的相同内容:
(defn place-caret-at-end [el]
(.focus el)
(doto (.createFromNodeContents goog.dom.Range el)
(.collapse false)
.select))
I have tested this in Chrome, Safari and FireFox, not sure about IE...
我已经在 Chrome、Safari 和 FireFox 中测试过这个,不确定 IE ...