按一下删除键删除整个单词
在文本框倒叙输入一文中提到了设置文本框焦点的javascript代码,今天就使用这段代码来做一个Demo。内容就是当删除单词时就一次性删除整个单词,如图所示:
下面我把示例代码贴上:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 6 <style> 7 .content {width: 300px;margin: 0 auto;} 8 </style> 9 <script src="http://cdn.staticfile.org/jquery/2.1.1-rc2/jquery.min.js"></script> 10 </head> 11 <body> 12 <div class="content"> 13 <textarea name="" id="demo" cols="30" rows="10"></textarea> 14 </div> 15 <script> 16 var getCursortPosition = function(ctrl) { 17 var CaretPos = 0; 18 // IE Support 19 if (document.selection) { 20 ctrl.focus(); 21 var Sel = document.selection.createRange(); 22 Sel.moveStart ('character', -ctrl.value.length); 23 CaretPos = Sel.text.length; 24 } 25 // Firefox support 26 else if (ctrl.selectionStart || +ctrl.selectionStart === 0) 27 {CaretPos = ctrl.selectionStart;} 28 return (CaretPos); 29 }; 30 31 var selectSomeText = function(element,begin,end) 32 { 33 if (element.setSelectionRange) 34 { 35 element.setSelectionRange(begin,end); 36 } 37 else if (element.createTextRange) 38 { 39 var range = element.createTextRange(); 40 range.moveStart("character",begin); 41 range.moveEnd("character",end); 42 range.select(); 43 } 44 }; 45 46 var delWholeWord = function(text, field, pos){ 47 var startIndex = pos; 48 if (field.charAt(pos-1) !== ' '){ 49 for (var i=pos-2;i>=0;i--){ 50 if (field.charAt(i) === ' ' || i === 0){ 51 startIndex = i; 52 break; 53 } 54 } 55 selectSomeText(text, startIndex, pos) 56 } 57 58 }; 59 $('#demo').keydown(function(event) { 60 if(event.keyCode !== 8) { 61 return; 62 } 63 var bodyText = $(this)[0]; 64 var bodyField = $(this).val(); 65 var pos = getCursortPosition(bodyText); 66 delWholeWord(bodyText, bodyField, pos); 67 }); 68 </script> 69 </body> 70 </html>