Javascript 在 ContentEditable div 中设置插入符位置

发布于 2024-11-23 20:17:56 字数 290 浏览 5 评论 0原文

我有一个设置了 contenteditable 的 div。这个 div 包含一个内部 div,如下所示:

<div contenteditable="true" class="key">
    <div class="innerKey">276</div>
</div>

奇怪的可编辑 div 结构源于对其他功能的需要。

我将如何使用 javascript 将插入符号位置设置为内部 div 内容的开头?

I have a div with contenteditable set. This div contains an inner div like so:

<div contenteditable="true" class="key">
    <div class="innerKey">276</div>
</div>

The odd editable div structure comes about from the need for other functionality.

How would I go about setting the caret position to the start of the content of the inner div using javascript?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

盗梦空间 2024-11-30 20:17:56

在 IE 以外的浏览器中 < 9,您可以非常简单地做到这一点,假设为简洁起见,您将“innerKey”的 id 添加到内部

var sel = window.getSelection();
var innerDiv = document.getElementById("innerKey");
var innerDivText = innerDiv.firstChild;
sel.collapse(innerDivText, 0);

jsFiddle: http://jsfiddle.net/Jaj6t/5/

如果需要支持IE< 9、你可以使用我的Rangy库来提供跨浏览器的DOM Range和Selection支持。

In browsers other than IE < 9, you can do this pretty simply, assuming for brevity that you added an id of "innerKey" to the inner <div>:

var sel = window.getSelection();
var innerDiv = document.getElementById("innerKey");
var innerDivText = innerDiv.firstChild;
sel.collapse(innerDivText, 0);

jsFiddle: http://jsfiddle.net/Jaj6t/5/

If you need to support IE < 9, you can use my Rangy library to provide the cross-browser DOM Range and Selection support.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文