1. 程式人生 > >在頁面游標處插入指定字串的具體實現,可直接引用

在頁面游標處插入指定字串的具體實現,可直接引用

//方法一:在游標處插入指定字串的具體實現
function insertAtCursor1(myValue) {
		 	 var myField = document.getElementById('ruleConfig');
			 //IE 瀏覽器
			 if (document.selection) {
				 myField.focus();
				 sel = document.selection.createRange();
				 sel.text = myValue;
				 sel.select();
			 }
		 
			 //FireFox、Chrome等
			 else if (myField.selectionStart || myField.selectionStart == '0') {
				 var startPos = myField.selectionStart;
				 var endPos = myField.selectionEnd;
		 
				 // 儲存滾動條
				 var restoreTop = myField.scrollTop;
				 myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
				 
				 if (restoreTop > 0) {
					myField.scrollTop = restoreTop;
				 }
				 
				 myField.focus();
				 myField.selectionStart = startPos + myValue.length;
				 myField.selectionEnd = startPos + myValue.length;
			 } else {
				 myField.value += myValue;
				 myField.focus();
			 }
		 }


          //其實倆種方法基本一樣,但是這種寫法更加簡單,推薦使用
			function insertAtCursor2(str){    
				var rule = document.getElementById("ruleConfig");
				var rulelen = rule.value.length;
				rule.focus();    
				if(typeof document.selection != "undefined")    
				{        
					document.selection.createRange().text = str;      
				}  
				else    
				{        
					rule.value = rule.value.substr(0,rule.selectionStart)+str+rule.value.substring(rule.selectionStart,rulelen);    
				}
			}