contenteditable,在文本末尾设置插入符号(跨浏览器)
在 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>
我相信在 FF 中它看起来像这样:
hey
<br />
what's up?
在 IE 中:
hey
<p>what's up?</p>
不幸的是,没有很好的方法来制作它这样每个浏览器都会插入
而不是 div 或 p 标签,或者至少我在网上找不到任何内容。
无论如何,我现在想做的是,当我点击按钮时,我希望将插入符号设置在文本末尾,所以它应该看起来像这样:
hey
what's up?|
任何方法这样它就可以在所有浏览器中工作吗?
例子:
$(document).ready(function()
{
$('#insert_caret').click(function()
{
var ele = $('#content');
var length = ele.html().length;
ele.focus();
//set caret -> end pos
}
}
output in 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 FF it would look something like this:
hey
<br />
what's up?
and in 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.
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
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下函数将在所有主流浏览器中执行此操作:
将插入符号放在开头几乎是相同的:它只需要更改传递给
collapse()
调用的布尔值。下面是一个创建用于将插入符号放在开头和结尾的函数的示例:The following function will do it in all major browsers:
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:不幸的是,蒂姆的出色答案对我来说仅适用于将其放在最后,而要放在开始处,我必须稍微修改它。
但不确定是否确实需要
focus()
和select()
。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.
Not sure though if
focus()
andselect()
are actually needed.这个(实时)示例展示了一个简短的函数
setCaretAtStartEnd
,它接受两个参数;将插入符号放置在 & 处的(可编辑)节点一个布尔值,指示放置位置(节点的开始或结束)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)如果您使用的是 google 闭包编译器,您可以执行以下操作(从 Tim 的答案中进行了一些简化):
ClojureScript 中也有同样的事情:
我已经在 Chrome、Safari 和 FireFox 中测试了这一点,不确定 IE...
If you are using the google closure compiler, you can do the following (somewhat simplified from Tim's answer):
Here's the same thing in ClojureScript:
I have tested this in Chrome, Safari and FireFox, not sure about IE...