ProgramingTip

입력 유형의 selectionStart / selectionEnd = "number"는 더 이상 Chrome에서 허용되지 않는 언어입니다.

bestdevel 2020. 10. 27. 23:02
반응형

입력 유형의 selectionStart / selectionEnd = "number"는 더 이상 Chrome에서 허용되지 않는 언어입니다.


우리의 응용 프로그램은 입력 필드에서 selectionStart를 사용하여 사용자가 화살표 키를 누를 때 다음 / 이전 필드로 자동으로 선택지 여부를 결정합니다 (즉, 선택이 텍스트의 어느 사용자가 이동하려는 화살표를 누를 때 ) 다음 필드, 이름)

Chrome은 이제 type = "number"에서 selectionStart를 사용하지 않습니다. 이제 예외가 발생합니다.

Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection.

다음을 참조하십시오.

https://codereview.chromium.org/100433008/#ps60001

http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#do-not-apply

type = "number"의 입력 필드에서 캐럿의 위치를 ​​결정하는 방법이 있습니까?


텍스트 / 검색, URL, 전화 및 암호로만 선택할 수 있습니다 . 번호 유형 입력에 대해 선택이있는 이유는 일부 장치에서 또는 일부 상황 (예 : 입력이 짧게 표시되는 경우 list)에서 캐럿이 없을 수 있기 때문입니다. 내가 사용하는 유일한 방법은 입력 유형을 텍스트로 변경하는 것입니다. 나는 여전히 입력을 변경하지 않고 할 방법을 찾고 있고, 찾을 것입니다 유형면 업데이트를 게시 할 것입니다.


.NET에 대한 간단한 해결 방법 (Chrome에서 테스트 됨)을 찾았습니다 setSelectionRange(). 은 단순히을 변경할 당신 수 있습니다 typetext사용하기 전에 setSelectionRange()다음에 다시 변경 number.

다음은 입력을 클릭 할 때마다 숫자 입력의 위치 4에 캐럿을 배치하는 jquery를 간단한 예제입니다 (동작을 보려면 입력에 5 개 이상의 숫자를 추가하십시오).

플 런커


현재 텍스트 선택을 허용하는 유일한 요소는 다음과 가능합니다.

<input type="text|search|password|tel|url">설명 :
whatwg : selectionStart 속성 .

HTMLInputElement 인터페이스대한 설명서를 읽고 입력 요소를 자세히 살펴볼 수 있습니다.

이 "문제"를 극복하기 위해 현재 가장 좋은 방법은 <input type="text">숫자 만 허용하는 마스크 / 제약 조건을 처리 하고 적용하는 것입니다. 요구 사항을 몇 가지 사항이 있습니다.

여기에서 이전 플러그인 중 하나의 라이브 데모를 볼 수 있습니다.

허용되는 비용을 selectionStart지원하는 요소를 확인할 수 있습니다 ( 입력 유형 속성 참조 ).

이행

// Fix: failed to read the 'selectionStart' property from 'HTMLInputElement'
// The @fn parameter provides a callback to execute additional code
var _fixSelection = (function() {
    var _SELECTABLE_TYPES = /text|password|search|tel|url/;
    return function fixSelection (dom, fn) {
        var validType = _SELECTABLE_TYPES.test(dom.type),
            selection = {
                start: validType ? dom.selectionStart : 0,
                end: validType ? dom.selectionEnd : 0
            };
        if (validType && fn instanceof Function) fn(dom);
        return selection;
    };
}());

// Gets the current position of the cursor in the @dom element
function getCaretPosition (dom) {
    var selection, sel;
    if ('selectionStart' in dom) {
        return _fixSelection(dom).start;
    } else { // IE below version 9
        selection = document.selection;
        if (selection) {
            sel = selection.createRange();
            sel.moveStart('character', -dom.value.length);
            return sel.text.length;
        }
    }
    return -1;
}

용법

// If the DOM element does not support `selectionStart`,
// the returned object sets its properties to -1.
var box = document.getElementById("price"),
    pos = getCaretPosition(box);
console.log("position: ", pos);

위의 예는 여기에서 사용할 수 있습니다 : jsu.fnGetCaretPosition ()


이는 jQuery Numeric Plugin, 버전 1.3.x를 사용하는 동안 발생했기 때문에 selectionStartselectionEnd래핑 try...catch{}하여 오류를 제한 할 수 있습니다.

출처 : https://github.com/joaquingatica/jQuery-Plugins/commit/a53f82044759d29ff30bac698b09e3202b456545


해결 방법으로 type="tel"입력되는 type="number"Chrome에서 기능을 제공 하며 제한이 없습니다 (Patrice가 지적한대로).


Chrome에서이 작업을 수행 할 수있는 한 가지 방법이 있습니다 (그리고 다른 브라우저에서도 가능하지만 Chrome은 여기에서 큰 문제입니다). 사용하여 window.getSelection()현재의 입력으로부터의 선택을 검색하고 테스트 (또는 앞에서) 선택하고있는 경우 표시되는 toString()선택 값. 입력 된 경우 커서가 입력의 끝에 입력 된 다음 입력으로 표시됩니다. 선택을 취소 할 작업을 되돌려 야합니다.

s = window.getSelection();
len = s.toString().length;
s.modify('extend', 'backward', 'character');
if (len < s.toString().length) {
    // It's not at the beginning of the input, restore previous selection
    s.modify('extend', 'forward', 'character');
} else {
    // It's at the end, you can move to the previous input
}

나는이 답변 에서이 아이디어를 얻었습니다 : https://stackoverflow.com/a/24247942


다음과 같이 지원되는 요소 만 포함 된 요소 검사를 존재합니다.

if (deviceIsIOS &&
    targetElement.setSelectionRange &&
    (
        targetElement.type === 'text' ||
        targetElement.type === 'search' ||
        targetElement.type === 'password' ||
        targetElement.type === 'url' ||
        targetElement.type === 'tel'
    )
) {

대신 :

if (deviceIsIOS && 
    targetElement.setSelectionRange && 
    targetElement.type.indexOf('date') !== 0 && 
    targetElement.type !== 'time' && 
    targetElement.type !== 'month'
) {

이 유형의 양식 필드에 대해 사용하지 않는 이벤트와 관련된 문제는 여전히 관련이있을 수 있습니다. 내가 볼 수있는 한 가지 유형의 필드는 "변경"이벤트를 통해 수신 할 수 있습니다.

이 유형의 필드에 대한 이벤트 문제에 대한 답을 찾는 동안 여기 에서이 기사를 찾았지만 테스트하는 동안 언급 한대로 "변경"이벤트에 의존 할 수 있음을 발견했습니다.


angularjs 웹 사이트 에서이 오류를 발표합니다.

입력에 사용자 지정 데이터 속성을 만들고 ng-blur ($ event 사용)도 사용했습니다.

호출이 호출 때 다음과 같이 'data-id'값에 액세스했습니다.

var id = $event.target.attributes["data-id"]

그리고 다음과 소비 야합니다.

var id = $event.target.attributes["data-id"].value

이 오류에 대해 아무데도 많지 않은 것 같에 여기에.


이 답변이 너무 늦었 음을 알고 있지만 여기에는 대부분의 브라우저 (이전 및 새)에 대해 모든 유형의 요소에 대해 selectionStart를 구현하는 플러그인이 있습니다.

https://github.com/adelriosantiago/caret

type="number"@ncohen의 답변을 사용하여 문제 를 처리하도록 업데이트했습니다 .


Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection.다음과 같이 해결하십시오 .

var checkFocus = false;
var originalValue = "";
$(document).ready(function() {
  $("input").focus(function() {
    var that = this;
    if ($('#' + $(this).context.id).attr("type") == "text") {
      setTimeout(function() {
        if (that.selectionStart != null || that.selectionEnd != null) {
          that.selectionStart = that.selectionEnd = 10000;
        }
      }, 0);
    } else if ($('#' + $(this).context.id).attr("type") == "number") {
      if (checkFocus) {
        moveCursorToEnd($('#' + $(this).context.id), $(this).context.id);
        checkValue($('#' + $(this).context.id))
        checkFocus = false;
      } else {
        $('#' + $(this).context.id).blur();
      }
    }
  });
});

function FocusTextBox(id) {
  checkFocus = true;
  document.getElementById(id).focus();
}

function checkValue(input) {
  if ($(input).val() == originalValue || $(input).val() == "") {
    $(input).val(originalValue)
  }
}

function moveCursorToEnd(input, id) {
  originalValue = input.val();
  input.val('');
  document.getElementById(id).focus();
  return originalValue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<button onclick="FocusTextBox('textid')">
   <input id="textid" type="number" value="1234" > 
</button>

참고 URL : https://stackoverflow.com/questions/21177489/selectionstart-selectionend-on-input-type-number-no-longer-allowed-in-chrome

반응형