Home > Web Front-end > JS Tutorial > js realizes pressing the delete key to delete the entire word with demo_javascript skills

js realizes pressing the delete key to delete the entire word with demo_javascript skills

WBOY
Release: 2016-05-16 16:36:50
Original
1580 people have browsed it

In the article Text Box Flashback Input, the javascript code for setting the focus of the text box is mentioned. Today I will use this code to make a demo. The content is to delete the entire word at once when deleting a word, as shown in the figure:

I will paste the sample code below:

<!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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template