您的位置:首页 > Web前端 > JavaScript

用js控制按钮事件,将指定内容添加到文本域的光标所在位置。

2014-08-03 13:42 495 查看
<pre class="javascript" name="code">
var fm = document.getElementsByTagName('form')[0];
var button = document.getElementsByName("button");
var textcontent = document.getElementById('textcontent');
//获取一个cookie的值
	function getCookie(index){
		var allcookies = document.cookie;  
		var cookie_pos = allcookies.indexOf(index);
		if (cookie_pos != -1){
			cookie_pos += index.length + 1;
			var cookie_end = allcookies.indexOf(";",cookie_pos); 
			if (cookie_end == -1){  
  				cookie_end = allcookies.length;  
			}  
			var value = unescape(allcookies.substring(cookie_pos, cookie_end)); 
		}    
		return value;  		
	}
	//获取文本中的光标位置
	 function getCursortPosition (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;
		}
		else if (ctrl.selectionStart || ctrl.selectionStart == '0')
			CaretPos = ctrl.selectionStart;
		return (CaretPos);
	}



//获取文本光标位置并设置一个cookie来存储光标时时变动的位置的函数
	var textpos = 0;
	textcontent.onclick  = function(){
		textpos = getCursortPosition (textcontent);
		document.cookie="textpos="+textpos;		
		textpos = getCookie("textpos");
	}
	//字符串的写入函数
	function content(string){	
		s = textcontent.value;
		fm.content.value  = s.substring(0,getCookie("textpos"))+string+s.substring(getCookie("textpos"));
	}
<pre class="php" name="code">	//点击按钮向表单中的文本域的光标处添加内容
	button[0].onclick  = function(){
		content('');
	}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: