最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to place caret inside an empty DOM Element Node - Stack Overflow

programmeradmin0浏览0评论

How can I place the caret (collapsed range) inside an empty element node. This code is supposed to work, but it doesnt.

node = document.getElementById('some-empty-strong-node')
range = document.createRange()
range.selectNodeContents(node)
window.getSelection().addRange(range)

Trying other tricks like adding an empty text node inside the element node or setting the range start inside the node and the range end somewhere else, and then collapsing the range also doesn't work. Anoyone has an Idea?

How can I place the caret (collapsed range) inside an empty element node. This code is supposed to work, but it doesnt.

node = document.getElementById('some-empty-strong-node')
range = document.createRange()
range.selectNodeContents(node)
window.getSelection().addRange(range)

Trying other tricks like adding an empty text node inside the element node or setting the range start inside the node and the range end somewhere else, and then collapsing the range also doesn't work. Anoyone has an Idea?

Share Improve this question asked Mar 30, 2011 at 15:57 disc0dancerdisc0dancer 9,37511 gold badges40 silver badges46 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

This is possible in Firefox and Opera, but impossible in both WebKit and IE <= 8.

WebKit has a long-standing bug to fix this: https://bugs.webkit/show_bug.cgi?id=15256 for the empty element case and https://bugs.webkit/show_bug.cgi?id=23189 for the general case of placing the caret at the start of a text node. Last I heard it's likely to be years before it's fixed.

IE <= 8 has all kinds of issues around selections, of which this is but one. IE 9 introduced DOM2 Range support and HTML5 Selection support and your code may well work in IE 9 (I can't test it right now).

A trick to that is to use a placeholder (so it disapear when placing the caret). Worked for me with "display: inline" div on chrome.

.css

[invisibleplaceholder]:empty:before{
    content: attr(invisibleplaceholder);
    color: transparent;
    cursor: text;
}

[invisibleplaceholder]:empty:focus:before{
    content: "";
}

.html

<div id="div1" contenteditable="true" invisbleplaceholder="."></div>
<div id="div2" contenteditable="true" invisibleplaceholder="."></div>

.js

$("body").click(function(){
        var range = document.createRange();
        var sel = window.getSelection();
        var node = $('div2')[0]; //your node
        range.setStart(node, 0); //your position in node
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
    });

I found that if you do this for Chrome:

<div id="select-this-element"> <br style="content: no-close-quote;" /></div>

It will work the same way that works in Firefox and Opera.

发布评论

评论列表(0)

  1. 暂无评论