js实现按一下删除键删除整个单词附demo

时间:2022-09-21 15:35:15

在文本框倒叙输入一文中提到了设置文本框焦点的javascript代码,今天就使用这段代码来做一个Demo。内容就是当删除单词时就一次性删除整个单词,如图所示:


js实现按一下删除键删除整个单词附demo

下面我把示例代码贴上:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<style>
.content {width: 300px;margin: 0 auto;}
</style>
<script src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script>
</head>
<body>
<div class="content">
<textarea name="" id="demo" cols="30" rows="10"></textarea>
</div>
<script>
var getCursortPosition = function(ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || +ctrl.selectionStart === 0)
{CaretPos = ctrl.selectionStart;}
return (CaretPos);
};
 
var selectSomeText = function(element,begin,end)
{
if (element.setSelectionRange)
{
element.setSelectionRange(begin,end);
}
else if (element.createTextRange)
{
var range = element.createTextRange();
range.moveStart("character",begin);
range.moveEnd("character",end);
range.select();
}
};
 
var delWholeWord = function(text, field, pos){
var startIndex = pos;
if (field.charAt(pos-1) !== ' '){
for (var i=pos-2;i>=0;i--){
if (field.charAt(i) === ' ' || i === 0){
startIndex = i;
break;
}
}
selectSomeText(text, startIndex, pos)
}
 
};
$('#demo').keydown(function(event) {
if(event.keyCode !== 8) {
return;
}
var bodyText = $(this)[0];
var bodyField = $(this).val();
var pos = getCursortPosition(bodyText);
delWholeWord(bodyText, bodyField, pos);
});
</script>
</body>
</html>