开发者

How to preserve selection when changing contents of an HTML element

开发者 https://www.devze.com 2023-03-22 23:23 出处:网络
I would like to be able to preserve the users\' selection when I change the contents of an HTML element.If the element is updated while the beginning or end of the selection happens to be inside, t开发

I would like to be able to preserve the users' selection when I change the contents of an HTML element. If the element is updated while the beginning or end of the selection happens to be inside, t开发者_Python百科he entire selection is lost. This also happens while dragging to create a selection, so that if the user is dragging a selection and the element's inner HTML is updated while the cursor is over the element, the user must start over.

I have a <span> that contains a time in the format 'hh:mm:ss am' and is updated each second. The length of the text never changes, so that isn't an issue.

I have tried the following:

var s = window.getSelection();
if (!s.isCollapsed) {
    var range = document.createRange();
    range.setStart(s.anchorNode,s.anchorOffset);
    range.setEnd(s.focusNode,s.focusOffset);
}

document.getElementById('time').innerHTML = new Date().toString();

if (typeof range != 'undefined') { s.removeAllRanges(); s.addRange(range); }

It's the best my research has yielded, but it doesn't seem to make a difference.

What should I do to prevent the selection from vanishing if it happens to start or end in this span?


You need to set the selection again: range.selectNodeContents(newNode);

newNode = document.getElementById("[span id]");
0

精彩评论

暂无评论...
验证码 换一张
取 消