DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> js實現按一下刪除鍵刪除整個單詞附demo
js實現按一下刪除鍵刪除整個單詞附demo
編輯:關於JavaScript     

在文本框倒敘輸入一文中提到了設置文本框焦點的javascript代碼,今天就使用這段代碼來做一個Demo。內容就是當刪除單詞時就一次性刪除整個單詞,如圖所示:

下面我把示例代碼貼上:

<!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>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved