本文介绍了模拟退格按钮JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个自定义的退格按钮,其逻辑与键盘上的退格"按钮相同.我使用以下代码:
I want to create a custom backspace button with the same logic as "backspace" button on a keyboard. I use the following code:
function backSpace()
{
var e = jQuery.Event("keyup");
e.which = 8; // # Some key code value
e.keyCode = 8;
$("mainDiv").trigger(e);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
<script src="formulas.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=no"/>
</head>
<button onclick="backSpace()">backSpace</button>
<body id="main" spellcheck="false">
<div id = "mainDiv" contenteditable="true"></div>
</body>
</html>
但是它不起作用.我不明白我在做什么错.我花了很多时间解决这个问题,但尚未解决.请帮帮我.
But it doesn't work. I don't understand what I'm doing wrong. I spend a lot of time for this problem, but I haven't solved it yet. Help me, please.
推荐答案
@CosLu答案的补充
Addition to @CosLu's Answer
function backSpace() {
p = document.getElementById("mainDiv");
c = getCaretPosition(p);
console.log(getCaretPosition(p));
str = $("#mainDiv").html();
if (c > 0 && c <= str.length) {
$("#mainDiv").focus().html(str.substring(0, c - 1) + str.substring(c, str.length));
p.focus();
var textNode = p.firstChild;
var caret = c - 1;
var range = document.createRange();
range.setStart(textNode, caret);
range.setEnd(textNode, caret);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
$.fn.setCursorPosition = function(pos) {
this.each(function(index, elem) {
if (elem.setSelectionRange) {
elem.setSelectionRange(pos, pos);
} else if (elem.createTextRange) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
});
return this;
};
function getCaretPosition(editableDiv) {
var caretPos = 0,
sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement("span");
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint("EndToEnd", range);
caretPos = tempRange.text.length;
}
}
return caretPos;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
</head>
<body>
<button onclick="backSpace()">backSpace</button>
<div id="mainDiv" contenteditable="true">aahahtext</div>
</body>
</html>
这篇关于模拟退格按钮JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!