2011-08-31 59 views
0

我在這個網站和其他人工作修復selectionStart和selectionEnd爲ie,並決定從這個site實現代碼。jquery文本輸入更改按鈕點擊

在一個簡單的html頁面中,有多個文本區域具有公共類和唯一的id。有幾個按鈕用作虛擬鍵盤。在關注任何文本文件並單擊按鈕時,將在光標位置處將文本放入該元素中。如果選擇的某些文本在Mozilla和Chrome中也可以正常工作。但問題在其他瀏覽器

歌劇 - 起搏文字是好的,但在選擇,而不是替換文本它 添加到選擇結束(即如果選擇從右做出向左,然後在左邊,反之亦然放置)。

ie8 - 行 無效參數`stored_range.moveToElementText(element);

整個代碼看起來像下面

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<title>selection test</title> 
<meta http-equiv="Content-type" content="text/html; charset=utf-8" /> 
<script type='text/javascript' src='js/jquery-1.4.2.js'></script> 
<script> 

window.onload = function() { 

jQuery('.iptext').live('focus', function(event) { 
      holdFocus=$(this); 
      holdFocus=holdFocus[0];//this is required 
     }); 
jQuery('.addchar').live('click', function(event) { 
      // Get focused textfield 
      if(holdFocus==null) 
      { 

      } 
      else 
      { 
      var element =holdFocus; 
if(document.selection){ 
    // The current selection 
    var range = document.selection.createRange(); 
    // We'll use this as a 'dummy' 
    var stored_range = range.duplicate(); 
    // Select all text 
    stored_range.moveToElementText(element); 
    // Now move 'dummy' end point to end point of original range 
    stored_range.setEndPoint('EndToEnd', range); 
    // Now we can calculate start and end points 
    element.selectionStart = stored_range.text.length - range.text.length; 
    element.selectionEnd = element.selectionStart + range.text.length; 
} 
        $(holdFocus).val(
        $(holdFocus).val().substring(0, holdFocus.selectionStart)+ 
        $.trim($(this).text())+ 
        $(holdFocus).val().substring(holdFocus.selectionEnd) 
      ); 
      } 
     }); 
}; 
</script> 
<style type="text/css" media="screen"> 
body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; } 
ul {display:block;} 
li { list-style: none;display:inline-block;width:20px;height:20px;background-color:#808000;} 
ul li a {display:block;text-decoration:none; } 
</style> 
</head> 
<body> 
    <input type="text" id="txt1" class="iptext" autocomplete="off" value="Testing String"> 
    <input type="text" id="txt2" class="iptext" autocomplete="off" value="Testing String"> 
<ul> 
<li><a href="#" class="addchar">a</a></li> 
<li><a href="#" class="addchar">b </a></li> 
<li><a href="#" class="addchar">c</a></li> 
<li><a href="#" class="addchar">d </a></li> 

</ul> 


</body> 
</html> 

這是一個小提琴link

回答

0

從你選擇把它從網站的代碼也不是萬無一失的。另外,在IE中,在處理插入符號或選擇位置之前,通常需要關注輸入(使用其方法focus())。

我建議my own jQuery plug-in用於處理文本輸入和textarea選擇。這是我所知道的唯一代碼,在IE中可以100%正確工作< 9.