我正在寻找一个明确的跨浏览器解决方案,当contentEditable ='on'重新获得焦点时,将光标/插入符号位置设置为最后一个已知位置。内容可编辑div的默认功能似乎是每次单击时将插入符号/光标移动到div中文本的开头,这是不可取的。
我相信当它们离开div焦点时,我必须将当前光标位置存储在一个变量中,然后当它们再次获得焦点时,重新设置此位置,但我还无法将其放在一起,或找到一个工作代码示例。
如果任何人有任何想法,工作代码片段或样本,我很乐意看到他们。
我真的没有任何代码,但这里是我有:
<script type="text/javascript">
// jQuery
$(document).ready(function() {
$('#area').focus(function() { .. } // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>
- PS.我已经尝试过这个资源,但似乎它不工作的a.也许只为textarea(How to move cursor to end of contenteditable entity)*
9条答案
按热度按时间tmb3ates1#
此解决方案适用于所有主流浏览器:
saveSelection()
附加到div的onmouseup
和onkeyup
事件,并将选择保存到变量savedRange
。restoreSelection()
附加到div的onfocus
事件,并重新选择保存在savedRange
中的选择。除非您希望在用户单击div时也恢复选择,否则这将非常有效(这有点不直观,因为通常您希望光标移动到您单击的位置,但为了完整性,包含了代码)
为了实现这一点,
onclick
和onmousedown
事件由cancelEvent()
函数取消,cancelEvent()
函数是一个跨浏览器函数,用于取消事件。cancelEvent()
函数还运行restoreSelection()
函数,因为在取消单击事件时,div不会接收焦点,因此除非运行此函数,否则不会选择任何内容。变量
isInFocus
存储它是否处于焦点上,并被更改为“false”onblur
和“true”onfocus
。这允许仅在div未处于焦点上时取消单击事件(否则您将根本无法更改选择)。如果您希望在通过单击聚焦div时更改所选内容,并且不恢复选择
onclick
(并且仅当使用document.getElementById("area").focus();
或类似物编程地将焦点给予元素时,然后简单地移除onclick
和onmousedown
事件。在这些情况下,也可以安全地删除onblur
事件以及onDivBlur()
和cancelEvent()
函数。如果你想快速测试的话,直接把这段代码放到html页面的主体中应该可以工作:
xdnvmnnf2#
这与基于标准的浏览器兼容,但在IE中可能会失败。我提供它作为一个起点。IE不支持DOM范围。
eivnm1vs3#
我编写了一个跨浏览器的范围和选择库Rangy,它包含了我下面发布的代码的改进版本。你可以使用selection save and restore module来回答这个问题,不过如果你在项目中没有做任何与选择相关的事情,也不需要这个库的大部分内容,我很想使用@Nico Burns的答案。
你可以使用IERange(http://code.google.com/p/ierange/)将IE的TextRange转换成类似DOM的Range,并将其与类似eyelidless的starting point的东西结合使用。就我个人而言,我只会使用IERange的算法来进行TextRange转换,而不是使用整个过程。IE的selection对象没有focusNode和anchorNode属性,但你应该可以只使用Range/<->从所选内容获取的TextRange。TextRange obtained from the selection instead.
我可能会把一些东西放在一起做这件事,将张贴回到这里,如果和当我这样做。
编辑:
我已经创建了一个脚本演示来实现这个功能。到目前为止,它在我尝试过的所有应用中都能正常工作,除了Opera 9中的一个bug,我还没有时间研究这个bug。它可以在IE 5.5、6和7、Chrome 2、Firefox 2、3和3.5以及Safari 4中工作,这些浏览器都是在Windows上运行的。
http://www.timdown.co.uk/code/selections/
注意,在浏览器中可以向后进行选择,这样焦点节点就位于选择的开始处,点击鼠标右键或左键会将插入符号移动到相对于选择开始处的位置。我认为在恢复选择时不可能重复这种情况,所以焦点节点总是位于选择的结束处。
我会在不久的某个时候把这篇文章写下来。
rjzwgtxy4#
我有一个相关的情况,我特别需要将光标位置设置为contenteditable div的END。我不想使用像Rangy这样的成熟库,而且许多解决方案都太重了。
最后,我使用了这个简单的jQuery函数,将克拉位置设置为contenteditable div的末尾:
理论很简单:在可编辑的末尾添加一个span,选择它,然后删除span --使光标位于div的末尾。您可以调整此解决方案,以便在任何需要的位置插入span,从而将光标置于特定位置。
用法很简单:
就是这样!
xiozqbni5#
我接受了Nico Burns的答案,并使用jQuery进行了计算:
div contentEditable="true"
You'll need jQuery 1.6 or higher:
x一个一个一个一个x一个一个二个一个x一个一个三个一个
des4xlb06#
在尝试了一下之后,我修改了上面的eyelidless的答案,并将其作为一个jQuery插件,这样您就可以执行以下操作之一:
请原谅长代码帖子,但它可能会帮助一些人:
f45qwnt87#
您可以利用现代浏览器支持的selectNodeContents。
e5njpo688#
在Firefox中,div的文本可能位于子节点(
o_div.childNodes[0]
)中pxiryf3j9#
我可能会在这个聚会上迟到,但是也许您可以将正在编辑的标记的当前值存储在一个变量中,而不是呈现给dom的值,而不是仅仅在前端操作dom。然后,您可以检测页面刷新并更改标记的innerHTML的值,或者在我的情况下,你只需要跟踪变化,并将其发送到后端。也许我的话不会做任何正义,所以我将写一个代码示例,为我的用例工作。
我希望这是有意义的,如果你想让我修改的答案没有打字膨胀,我愿意和能够。如果这对你们的工作,请让我知道,我认为这是一个简单得多的解决方案,然后试图重新配置光标如何你想要的个人。