2012-12-03 2 views
0

다음과 같은 방법으로 입력 텍스트를 삭제하려고하는데 Mozilla에서 작동하지 않는 사람이 누구입니까?
IE에서 잘 작동합니다.시작 및 끝 위치를 사용하여 입력에서 문자 삭제 javascript

var start = txt.selectionStart; 
var end = txt.selectionEnd; 
var selectedStr = txt.value.toString().substring(start, end); 
txt.value = txt.value.toString().replace(selectedStr, ""); 
+0

가 왜 문자열에'toString'를 호출 바이올린하십시오 –

+0

을 만들? 또한 : 입력의 일부를 선택 했습니까? 그렇다면, substring은 유일하다. 왜냐하면'replace'가 첫 번째 매치 only_를 대체 할 것이기 때문이다. 그렇지 않다면 : 선택되지 않은 입력을 자르고 끝내기 위해'txt.value.substring (0, txt.selectionStart) + txt.value.substring (txt.selectionEnd)'을 시도하십시오 –

답변

1

것 같습니다. 두 가지 접근 방식이 필요합니다. 하나는 IE < 9이고 다른 하나는 selectionStartselectionEnd 속성을 지원하는 브라우저입니다. 여기에 방법은 다음과 같습니다

데모 : http://jsfiddle.net/hwG7f/1/

코드 :

function deleteSelected(input) { 
    input.focus(); 
    if (typeof input.selectionStart == "number") { 
     var start = input.selectionStart, 
      end = input.selectionEnd, 
      val = input.value; 
     if (start != end) { 
      input.value = val.slice(0, start) + val.slice(end); 
      input.setSelectionRange(start, start); 
     } 
    } else if (typeof document.selection != "undefined") { 
     document.selection.createRange().text = ""; 
    } 
} 
1

모질라 (그리고 다른 브라우저) document.selection을 사용하여 다른 구현을 가지고 window.getSelection() 그래서 당신은 그 방법/특성 및 레거시 지원 테이블에 따라 당신의 코드를 조정해야합니다. 당신을 위해 이것을 표준화하는 많은 라이브러리를 사용할 수 있습니다.

var selectedStr = ''; 
if (window.getSelection) { 
    var selectedText = window.getSelection().toString() 
} 
+0

@ OP는 코드가 IE에서 일하면서, 거짓말 이었나요? – David

+0

거짓말인지 전혀 모르겠지만'document.selection.createRange()'는'selectionStart' 대신에'selectionEnd'가 잘못되었습니다. –

+0

충분히 많은 사람들이 고려해야 할 브라우저가 많습니다.하지만 입력 내용을 캡처 할 수 없다는 성명도 잘못되었습니다. f.ex : http://jsfiddle.net/jM4ZY/ (chrome) – David

0

값을 교체하는 것은이 접근하는 올바른 방법이 아니다 : 여기

는 웹킷에서 작동하는 코드 예제입니다. 선택을 앞 문자열의 덩어리를 복용하고 다음보십시오 : 여기
var start = txt.selectionStart; 
var end = txt.selectionEnd; 
txt.value = txt.value.substring(0,start) + txt.value.substring(end); 

는 데모입니다 : http://jsfiddle.net/BuMUu/1/

-1
var str = "yourString" 
str = str.substring(1,str.length-1) 
+0

이 질문과 관련하여 어떤 점이 있습니까? – Amberlamps

0

지정한 selectionStart는 IE9 +에서 작동합니다.

죄송 합니다만, 직접 ""으로 설정하지 마십시오. 당신은 텍스트 입력에서 선택한 텍스트를 삭제하려는 것처럼


<input type="text" id="txt" /> 
<input type="button" value="Clear" id="clear" />​ 

function clear() { 
    var txt = document.getElementById('txt'); 
    txt.value = ""; 
} 
$('#clear').click(function(){clear()});​ 
관련 문제