Textarea サポートタブを作成する JavaScript メソッド key_javascript スキル

WBOY
リリース: 2016-05-16 15:52:24
オリジナル
1326 人が閲覧しました

この記事の例では、JavaScript で Textarea がタブ ボタンをサポートできるようにする方法について説明します。皆さんの参考に共有してください。具体的な実装方法は以下の通りです。

HTMLTextAreaElement.prototype.getCaretPosition = function () {
//return the caret position of the textarea
 return this.selectionStart;
};
HTMLTextAreaElement.prototype.setCaretPosition = function (position) {
//change the caret position of the textarea
 this.selectionStart = position;
 this.selectionEnd = position;
 this.focus();
};
HTMLTextAreaElement.prototype.hasSelection = function () {
//if the textarea has selection then return true
 if (this.selectionStart == this.selectionEnd) {
  return false;
 } else {
  return true;
 }
};
HTMLTextAreaElement.prototype.getSelectedText = function () {
//return the selection text
 return this.value.substring(this.selectionStart, this.selectionEnd);
};
HTMLTextAreaElement.prototype.setSelection = function (start, end) {
//change the selection area of the textarea
 this.selectionStart = start;
 this.selectionEnd = end;
 this.focus();
};
var textarea = document.getElementsByTagName('textarea')[0]; 
textarea.onkeydown = function(event) {
 //support tab on textarea
 if (event.keyCode == 9) { //tab was pressed
  var newCaretPosition;
  newCaretPosition = textarea.getCaretPosition() + " ".length;
  textarea.value = textarea.value.substring(0, textarea.getCaretPosition()) + " " + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
  textarea.setCaretPosition(newCaretPosition);
  return false;
 }
 if(event.keyCode == 8){
 //backspace
  if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == " ") {
  //it's a tab space
   var newCaretPosition;
   newCaretPosition = textarea.getCaretPosition() - 3;
   textarea.value = textarea.value.substring(0, textarea.getCaretPosition() - 3) + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
   textarea.setCaretPosition(newCaretPosition);
  }
 }
 if(event.keyCode == 37){ //left arrow
  var newCaretPosition;
  if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == " ") {
  //it's a tab space
   newCaretPosition = textarea.getCaretPosition() - 3;
   textarea.setCaretPosition(newCaretPosition);
  } 
 }
 if(event.keyCode == 39){
 //right arrow
  var newCaretPosition;
  if (textarea.value.substring(textarea.getCaretPosition() + 4, textarea.getCaretPosition()) == " ") {
  //it's a tab space
   newCaretPosition = textarea.getCaretPosition() + 3;
   textarea.setCaretPosition(newCaretPosition);
  }
 } 
}

ログイン後にコピー

この記事が皆様の JavaScript プログラミング設計に役立つことを願っています。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!