문제

텍스트 상자와 링크 버튼이 있습니다. 텍스트를 작성하면 텍스트를 선택한 다음 일부 텍스트를 선택한 다음 링크 버튼을 클릭하고 텍스트 상자에서 선택한 텍스트는 메시지 상자와 함께 표시되어야합니다.

어떻게하니?


아래 텍스트 상자의 제출 버튼을 클릭하면 메시지 상자에 Lorem Ipsum이 표시되어야합니다. "Lorem Ipsum"이이 지역에서 선택되기 때문입니다.


페이지에서 텍스트를 선택하고 제출 버튼을 클릭하면 작동 중이지만 텍스트 상자에 텍스트를 작성하고 만들면 그렇지 않습니다. 다른 공간을 클릭하면 텍스트 상자 선택이 취소되기 때문입니다.

이제 문제는 TextBox에서 텍스트를 선택하고 다른 컨트롤 또는 공간을 클릭하면 선택한 텍스트가 여전히 선택되어야한다는 것입니다.

어떻게해야합니까?

도움이 되었습니까?

해결책

좋아, 여기에 내가 가진 코드가있다.

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  {// Standards Compliant Version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  {// IE Version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

문제, IE에 제공하는 코드는 많은 사이트에 제공되지만 현재 시스템에서 IE6 사본에서 작동 할 수는 없습니다. 아마도 그것은 당신에게 효과가있을 것입니다. 그래서 내가 그것을주는 이유입니다.
당신이 찾는 트릭은 아마도 .focus () 호출 일 것입니다. textRea에 초점을 돌려주는 것입니다.

업데이트] OnkeyDown 이벤트와 함께 올바른 결과 (선택 컨텐츠)를 받았습니다.

document.onkeydown = function (e) { ShowSelection(); }

따라서 코드가 정확합니다. 다시 한 번, 문제는 버튼을 클릭하여 선택하는 것입니다 ... 계속 검색합니다.

업데이트] 나는 li 태그를 클릭하면 이전 선택을 선택하지 않기 때문에 태그. 위의 코드는 간단하게 작동합니다 input 그래도 버튼 ...

다른 팁

다음은 마우스 업에서 텍스트 선택이 발생한다는 사실을 바탕으로 훨씬 간단한 솔루션입니다. 이벤트 리스너를 추가합니다.

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

이것은 모든 브라우저에서 작동합니다.

키보드를 통해 선택을 처리하려면 다른 이벤트 리스너를 추가하십시오. keyup, 동일한 코드로.

그렇지 않은 경우 Firefox Bug는 2001 년에 다시 제출되었습니다 (예, 14 년 전), 우리는 할당 된 값을 대체 할 수 있습니다. window.mySelection ~와 함께 window.getSelection().toString(), IE9+ 및 모든 현대식 브라우저에서 작동하며 DOM의 텍사스 비 텍사스 부분에서 선택을받습니다.

function disp() {
  var text = document.getElementById("text");
  var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />

Opera, Firefox 및 Safari의 경우 다음 기능을 사용할 수 있습니다.

function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}

그런 다음 텍스트 필드 요소 (TextArea 또는 입력 요소와 같은)에 대한 참조를 함수로 전달합니다.

alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));

또는 원한다면u003Ctextarea> <입력> 자체의 getSelection () 함수를 갖기 위해 :

HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};

그럼 당신은 그냥 할 것입니다 :

alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());

예를 들어.

큰 팬 jQuery-textrange

아래는 매우 작고 독립적 인 예입니다. 다운로드 jquery-textrange.js를로드하고 동일한 폴더로 복사하십시오.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery-textrange</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-textrange.js"></script>

<script>
/* run on document load **/
$(document).ready(function() {
    /* run on any change of 'textarea' **/
    $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
        /* The magic is on this line **/
        var range = $(this).textrange();
        /* Stuff into selectedId.  I wanted to store this is a input field so it can be submitted in a form. **/
        $('#selectedId').val(range.text);
    });
});
</script>
</head>
<body>

    The smallest example possible using 
    <a href="https://github.com/dwieeb/jquery-textrange">
       jquery-textrange
    </a><br/>
    <textarea id="textareaId" >Some random content.</textarea><br/>
    <input type="text"  id="selectedId"  ></input>

</body>
</html>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top