我是 JavaScript 的新手,希望这里有人可以帮助我解决以下问题:
主要在 IE 8 中寻找解决方案 - 如果它可以更好地覆盖其他浏览器/版本。 我有一个页面,其中只有一个动态创建并包含文本和 HTML 标记的 contenteditable div。 在页面上我想添加一个按钮,将光标位置的某些文本插入到此 div 中。
到目前为止,我有以下代码,只要我在 div 中选择一个文本,它就可以正常工作,但如果我只是将光标放在那里而没有选择任何内容,它会将我的文本插入到 div 之外。
我怎样才能让它总是在光标位置添加我的文本,就像现在在选择位置一样? (我什至不需要它来替换一个选择,因为它只需要在光标位置。此外,这只需要一个特定的 div。)
我的代码:
<html>
<head>
<script type="text/javascript">
function test()
{
var input = "TEST";
document.selection.createRange().pasteHTML(input);
}
</script>
</head>
<body>
<div id="myDiv" contenteditable>This is a test text.</div><br />
<button type="button" onclick="test()">Test</button>
</body>
</html>
谢谢你的帮助,蒂姆
最佳答案
你的问题是 <button>
元素窃取焦点并在 click
时破坏选择事件已在 IE 中触发。你可以制作 <button>
不可选择,这将阻止它能够获得焦点。这是使用 unselectable
attribute 完成的在 IE 中:
<button type="button" unselectable="on" onclick="test()">Test</button>
我认为另一种不太好的选择是使用 mousedown
事件并阻止默认操作:
<button type="button" unselectable="on"
onmousedown="test(); return false">Test</button>
您可以找到一个跨浏览器的功能,在 contenteditable
中的当前光标位置插入 HTML。这里的元素:
https://stackoverflow.com/a/6691294/96100
最后一点:contenteditable
不是 bool 属性所以严格来说你应该给它一个值(即 <div contenteditable="true">
),虽然 <div contenteditable>
在我试过的所有浏览器中都有效。
关于JavaScript:获取光标在 contenteditable div 中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19620439/