Development Tip

HTML 입력 필드를 클릭해도 초점이 맞지 않습니다.

yourdevel 2020. 10. 28. 21:10
반응형

HTML 입력 필드를 클릭해도 초점이 맞지 않습니다.


문제가 있는데 정확히이 동작의 원인을 파악할 수 없습니다. textareaHTML 양식의 입력 필드 및에 액세스 할 수 없습니다 .

불행히도 JS, HTML 및 CSS는 매우 크기 때문에 여기에 모두 게시 할 수는 없습니다.

아무도이 이상한 동작을 디버깅 할 때 무엇을 찾아야하는지 말해 줄 수 있습니까?

최신 정보

커서를 input필드 위로 이동하면 텍스트 커서를 볼 수 있지만 클릭하면 필드에 포커스가 없습니다. Tab를 눌러 필드에 액세스 할 수 있으며 마우스 오른쪽 버튼으로 클릭 한 다음 필드를 클릭하면 해당 필드에 대한 포커스도 얻습니다.

... 아니요, disabled또는 readonly속성 이 없습니다 ;-)


클릭하면 필드에 초점이 맞지 않습니다. "탭 키"를 눌러 필드에 액세스 할 수 있습니다.

mousedown 이벤트에 대한 기본 작업을 취소 한 것 같습니다 . HTML과 JS에서 onmousedown 핸들러를 검색하고 읽는 행을 찾으십시오.

return false;

이 선은 클릭으로 초점을 맞추지 못하게 할 수 있습니다.


Re : 귀하의 의견,이 처리기를 추가하는 코드를 편집 할 수 없다고 가정합니다. 가능한 경우 가장 간단한 해결책은 return false;문을 제거하는 것입니다.

덮어 쓰지 않고 이벤트 트리거에 기능을 추가하는 방법이 있습니까?

핸들러가 연결되는 방법에 따라 다릅니다. 기존 등록 방법 (예 : element.onmousedown )을 사용하여 첨부 된 경우 래퍼를 만들 수 있습니다.

var oldFunc = element.onmousedown;
element.onmousedown = function (evt) {
    oldFunc.call(this, evt || window.event);
}

이 "래퍼"는 false를 반환하지 않으므로 요소에 대한 기본 작업 (포커스)을 취소하지 않습니다. 이벤트가 addEventListener 또는 attachEvent 와 같은 고급 등록 방법을 사용하여 첨부 된 경우 함수 이름 / 참조를 사용하여 이벤트 처리기를 제거하고 위와 유사한 래핑 된 함수로 다시 연결할 수 있습니다. 추가 된 익명 함수이고 이에 대한 참조를 얻을 수없는 경우 유일한 해결책은 다른 이벤트 처리기를 연결하고 element.focus () 메서드를 사용하여 수동으로 요소에 초점을 맞추는 것입니다.


나도이 문제가 있었다. disableSelection()내 입력 필드가 포함 된 부모 DIV에서 jQuery UI 메서드를 사용했습니다 . Chrome에서 입력 필드는 영향을받지 않았지만 Firefox에서는 입력 (및 텍스트 영역도)이 클릭에 집중되지 않았습니다. 여기서 이상한 점은 이러한 입력에 대한 클릭 이벤트가 작동한다는 것입니다.

해결책은 disableSelection()부모 DIV에 대한 메서드 를 제거하는 것이 었습니다 .


나는 이것이 매우 오래된 스레드라는 것을 알고 있지만 이것은 최근에 나에게 일어났습니다. 그것을 알아내는 데 시간이 걸렸습니다.

이 같은 문제는 'label'태그 쌍 안에 'input'요소를 넣어서 발생할 수 있습니다.

필자의 경우 'div'태그 쌍을 만들려고했지만 실수로 'label'태그 쌍을 만든 다음 DOM을 사용하여 텍스트 입력 필드 'input type = "text"..'를 삽입했습니다.

화면에 정상적으로 표시되었지만 텍스트 필드 중 하나를 클릭했을 때 커서가 계속해서 첫 번째 '입력'으로 돌아가고 정말 이상하게 작동했습니다.

이 행동은 미묘하고 이런 종류의 실수를 저질렀을 때 예상했던 것이 전혀 아니기 때문에 이것을 알아내는 데 시간이 걸렸습니다.

bsnider


onclick="this.select()"입력 태그 속성을 사용하십시오 .


나는 얼마 전에 같은 문제로 어려움을 겪었습니다. 모달 jquery-ui 대화 상자에서 jquery.layout 플러그인을 사용하고 있었는데 그 안에있는 필드에 액세스 할 수 없었습니다.

그것은 것으로 나타났다 z-index문제 (일부는 div내가 그들을 클릭하지 수 있도록, 내 입력 필드 끝났다). 그것을 확인하고 z-index입력 필드 값을 변경 해야합니다.


이는 <label>양식에 불균형 태그 가있을 때 가끔 발생 합니다.


저도이 문제가 있었고 제 경우에는 글꼴의 색상이 배경과 같은 색상이라는 것을 알았으므로 아무 일도 일어나지 않은 것처럼 보였습니다.


모바일 장치에서 DOM과 함께 캔버스를 사용하는 동안이 문제에 직면하면 대답이 Ashwin G완벽하게 작동했지만 javascript를 통해 수행했습니다.

var element = document.getElementById("myinputfield");
element.onclick = element.select();

그 후 모든 것이 완벽하게 작동했습니다.


위의 모든 답변을 읽었으며 일부는 저를 문제로 안내했지만 문제에 대한 해결책은 아닙니다.

문제의 근본 원인은 disableSelection(). 그것은 모든 문제를 야기하고 있지만 그것을 제거하는 것은 해결책이 아닙니다. (적어도 2016 년 또는 약간 이전에), 터치 스크린 장치 에서 jQuery로 객체를 이동하려면 이것을 사용해야합니다. .

해결책은 disableSelection()정렬 가능한 요소 에를 남겨두고 바로 위에 바인딩 작업을 추가하는 것입니다.

 $('#your_selector_id form').bind('mousedown.ui-disableSelection selectstart.ui-disableSelection', function(event) {
    event.stopImmediatePropagation();
 })

formJQuery와 요소는 몇 가지 요소에 전파를해야 할 수도로서, 양식에 전파를 중지하는 단지입니다.


.NET Framework에 열을 배치하지 않으면 부트 스트랩에서 발생할 수 있습니다 <div class ='row'>. 열 부동은 지워지지 않으며 이전 열 위에있는 다음 열을 얻을 수 있으므로 클릭이 예상되는 dom 요소에 도달하지 않습니다.


비슷한 문제가 발생했습니다. 이유를 알 수 없었지만 다음 코드를 사용하여 수정했습니다. 어떻게 든 빈 입력에만 집중할 수는 없습니다.

$('input').click(function () {
        var val = $(this).val();
        if (val == "") {
            this.select();
        }
    });

이 코드 때문에이 문제가 발생했습니다.

$("#table tbody tr td:first-child").bind("mousedown", function(e){
    e.preventDefault();
    $(this).parents('tr').removeClass('draggable');
});

제거하여 해결했습니다.

e.preventDefault ();

새 코드 :

$("#table tbody tr td:first-child").bind("mousedown", function(){
    $(this).parents('tr').removeClass('draggable');
});

나는 JQuery UIBootstrap을 사용하고 있으므로이 문제에 직면했으며 정상적인 경우 텍스트 영역이나 입력 파일이 본질적으로 편집 가능한 것처럼 둘 사이의 충돌이라고 생각하지만 위의 모든 답변을 테스트 한 후이 솔루션을 만들었지 만 없음 문제점을 해결 모든 주요 브라우저에 대한 크로스 브라우저 지원을 ,하지만 난 그것을 해결하고 난 당신이 입력 텍스트와 텍스트 영역에서 사용할 수 있습니다 내 솔루션을 공유하고

(데스크톱에서 테스트 됨 : IE (모든 버전), Chrome, Safari, Windows Edge, Firefox, Visual Studio Cordova Ripple Viewer on Windows 및 Visual Studio Cordova Windows 10 Store 앱)

(모바일에서 테스트 : Chrome, Firefox, Android 인터넷 브라우저 및 Visual Studio Cordova 앱 (Android 및 Visual Studio Cordova Windows 8 + 8.1 + 10 전화 앱))

다음은 HTML 코드입니다.

<textarea contenteditable id="textarea"></textarea>

이것은 CSS 코드입니다.

textarea {
    -webkit-user-select: text !important;
    -khtml-user-select: text !important;
    -moz-user-select: text !important;
    -ms-user-select: text !important;
    user-select: text !important;
    /*to make sure that background color and text color is not the same (from the answers above)*/
    background-color:#fff !important;
    color:#733E27 !important;
 }        

이것은 문서 준비의 JQuery 코드입니다.

$("textarea").click(function() {
        setTimeout(function(){
            $("textarea").focus();
            //add this if you are using JQuery UI (From The Solutions Above)
            $("textarea").enableSelection();
            var val = $("textarea").val();
            if (val.charAt(val.length-1) !== " " && val.length !== 1) {
                alert(val.length);
                val += " ";
            }
            $("textarea").val(val);
        }, 0);
    });

    if (navigator.userAgent.indexOf('Safari') !== -1 || navigator.userAgent.indexOf('Chrome') !== -1) {
        //alert('Its Safari or chrome');
        $("textarea").onfocus(function(e) {
            setTimeout(function(){
                var end;
                if ($("textarea").val === "") {
                    end = 0;
                } else {
                    end = $("textarea").val.length;
                }
                if ($("textarea").setSelectionRange) {
                    var range = document.getElementById('textarea').createTextRange();
                    if (range) {
                        setTimeout(range, 0, [end, end]);
                    } else { // IE style
                        var aRange = document.getElementById('textarea').createTextRange();
                        aRange.collapse(true);
                        aRange.moveEnd('character', end);
                        aRange.moveStart('character', end);
                        aRange.select();
                    }
                }
                e.preventDefault();
                return false;
            }, 0);
        });
    }

내 웹 애플리케이션 ( www.gahwehsada.com) 에서 테스트 할 수 있습니다.


당신이 말할 때

and nope, they don't have attributes: disabled="disabled" or readonly ;-)

HTML, 페이지의 소스 코드 또는 DOM을 보는 것입니까?

Chrome 또는 Firefox로 DOM을 검사하면 javasript 또는 오버레이 div를 통해 입력 필드에 추가 된 속성을 볼 수 있습니다.


다른 사람이이 답변을 찾고있는 경우 비슷한 문제가 발생하여 입력 태그의 Z- 인덱스를 변경하여 해결했습니다. 분명히 다른 div가 너무 멀리 확장되어 입력 상자와 겹칩니다.


I had this problem for over 6 months, it may be the same issue. Main symptom is that you can't move the cursor or select text in text inputs, only the arrow keys allow you to move around in the input field. Very annoying problem, especially for textarea input fields. I have this html that gets populated with 1 out of 100s of forms via Javascript:

<div class="dialog" id="alert" draggable="true">
    <div id="head" class="dialog_head">
        <img id='icon' src='images/icon.png' height=20 width=20><img id='icon_name' src='images/icon_name.png' height=15><img id='alert_close_button' class='close_button' src='images/close.png'>
    </div>
    <div id="type" class="type"></div>
    <div class='scroll_div'>
        <div id="spinner" class="spinner"></div>
        <div id="msg" class="msg"></div>
        <div id="form" class="form"></div>
    </div>
</div>

Apparently 6 months ago I had tried to make the popup draggable and failed, breaking text inputs at the same time. Once I removed draggable="true" it works again!


I just found another possible reason for this issue, some input textboxes were missing the closing "/", so i had <input ...> when the correct form is <input ... />. That fixed it for me.


In my case it was Bootstrap popup in opened state. Text input was in another calendar popup on top of Bootstrap one, input got its focus back after removing tabindex="-1" attribute from Bootstrap modal.


iPhone6 chrome

Problem for me was placing the input field inside <label> and <p>

like this :

<label>
  <p>
     <input/>
  </p>
</label>

I changed them to

<div>
  <div>
     <input/>
  </div>
</div>

And it works for me .

After check this answer, Please check other answers in this page, this issue may have different reasons


This will also happen anytime a div ends up positioned over controls in another div; like using bootstrap for layout, and having a "col-lg-4" followed by a "col-lg=8" misspelling... the right orphaned/misnamed div covers the left, and captures the mouse events. Easy to blow by that misspelling, - and = next to each other on keyboard. So, pays to examine with inspector and look for 'surprises' to uncover these wild divs.

Is there an unseen window covering the controls and blocking events, and how can that happen? Turns out, fatfingering = for - with bootstrap classnames is one way...


I had the same problem. I eventually figured it out by inspecting the element and the element I thought I had selected was different element. When I did that I found there was a hidden element that had z-index of 9999, once I fixed that my problem went away.


the problem for me was that I was using class="modal fade", I changed it for class="modal hide". That solved the issue.


I had the same problem. Tore my hair for hours trying all sorts of solutions. Turned out to be an unclosed a tag.Try validate your HTML code, solution could be an unclosed tag causing issues


I had this issue using Bootstrap + contact form 7. I for some reason I put the label as the container of the form and that was the issue for not being selectable on mobile.

<label>
    <contact form>...</contact form>
</label>

Seemed to break all inputs except the first input and the submit.


I had the same issue and the fix was to remove the placeholders and I changed the design of the form to use labels instead of placeholders...


I had this issue caused by a sort of overlap of a div element with a bootstrap class ="row" over a "brother" div element with the class="col", the first hid the focus of the second div element.

I solved taking outer the div row element from that level of the divs' tree and so rebalancing bootstrap logical hierarchy based on the row and col classes.


I had this same issue just now in React.

I figured out that in the Router, Route. We cannot do this as it causes this issue of closing the mobile keyboard.

<Route 
 path = "some-path"
 component = {props => <MyComponent />}
 />

Make sure and use the render instead in this situation

<Route 
 path = "some-path"
 render = {props => <MyComponent />}
 />

Hope this helps someone

Daniel

참고URL : https://stackoverflow.com/questions/3724749/html-input-fields-does-not-get-focus-when-clicked

반응형