Contenteditable div-按钮点击事件与其他元素点击事件有何不同



我正试图通过单击其他元素在内容可编辑div的当前光标位置插入文本。如果我点击按钮,但不使用任何其他元素,这将非常完美。我的意思是,对于它在光标位置插入的按钮,但对于任何其他元素的单击,它总是添加div的起始位置。下面是一个例子,其中包括按钮点击和DIV点击(它不适用于任何其他标记(。这两次点击有什么区别吗?如何使DIV点击与按钮点击完全一样。请注意,我没有使用JQUERY(但如果VUEJS有任何解决方案,我很好(。非常感谢。

这是jsfiddle链接http://jsfiddle.net/jwvha/2727/

function insertTextAtCursor(text) {
document.getElementById('pre').focus();
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
sel.removeAllRanges();
sel.addRange(range);
}
body {
background-color: #CCC;
}
div {
border: 1px #000 solid;
background-color: #FFF;
width: 900px;
margin-left: auto;
margin-right: auto;
text-align: center;
margin-top: 20px;
margin-bottom: 20px;
vertical-align: center;
padding: 30px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Editor</title>
</head>
<body>
<div contenteditable id="pre">
Update text Here . This is contenteditable div
</div>
<div>
<input type="button" onClick="insertTextAtCursor('TEXT')" value="Click here to insert text above"> ( This button inserts text at the cursors current positions)
</div>
<div onClick="insertTextAtCursor('TEXT')">
<b>Click here to insert in the above  contenteditable div </b> ( This won't insert at the current position , but always at the position 1)
</div>
</body>
</html>

与许多其他元素不同,按钮不会在点击时获得焦点。由于您在函数中依赖焦点,在DOM树中出现成功的click事件(由mouseup+mousedown组成(后,您的焦点将首先设置在div上。您可以通过监听mousedown事件并调用event.preventDefault()来避免这种情况,也可以在触发click(即onmousedown(之前简单地触发函数。

这是对另一篇文章的回答,它很好地解释了一切。

var prevented = document.getElementById("prevented");
prevented.addEventListener('mousedown', event => event.preventDefault());
function insertTextAtCursor(text) {
document.getElementById('pre').focus();
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
sel.removeAllRanges();
sel.addRange(range);
}
body {
background-color: #CCC;
}
div {
border: 1px #000 solid;
background-color: #FFF;
width: 500px;
margin-left: auto;
margin-right: auto;
text-align: center;
margin-top: 20px;
margin-bottom: 20px;
vertical-align: center;
padding: 30px;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Editor</title>
</head>
<body>
<div contenteditable id="pre">
Update text Here . This is contenteditable div
</div>
<div>
<input type="button" onClick="insertTextAtCursor('TEXT')" value="Click here to insert text above"> ( This button inserts text at the cursors current positions)
</div>
<div onClick="insertTextAtCursor('TEXT')" id="prevented">
<b>Click here to insert in the above  contenteditable div </b> ( This won't insert at the current position , but always at the position 1)
</div>
</body>
</html>

最新更新