简体   繁体   English

单击时 HTML 输入字段不会获得焦点

[英]HTML input fields does not get focus when clicked

I have a problem and I can't figure out what exactly is causing this behavior.我有一个问题,我无法弄清楚究竟是什么导致了这种行为。 I cannot access my input fields and textarea s on my HTML form.我无法访问我的 HTML 表单上的输入字段和textarea

Unfortunately, the JS, HTML and CSS are very large, so I can't really post it all here.不幸的是,JS、HTML 和 CSS 非常大,所以我不能真正在这里发布。

Can anybody tell me what to look for when debugging this strange behavior?谁能告诉我在调试这种奇怪的行为时要寻找什么?

UPDATE更新

If I move the cursor over the input field I can see the text cursor, but when I click it the field does not get the focus.如果我将光标移到input字段上,我可以看到文本光标,但是当我单击它时,该字段没有获得焦点。 I can access the field via pressing the Tab key and if I right click on it and then click on the field I also get the focus for it.我可以通过按Tab键访问该字段,如果我右键单击它然后单击该字段,我也会获得它的焦点。

...and nope, they don't have the disabled or readonly attributes ;-) ...不,他们没有disabledreadonly属性;-)

when i click it the field does not get the focus.当我单击它时,该字段没有获得焦点。 i can access the field via pressing the "tab-key"我可以通过按“tab键”访问该字段

It sounds like you've cancelled the default action for the mousedown event.听起来您已经取消了mousedown事件的默认操作。 Search through your HTML and JS for onmousedown handlers and look for a line that reads.在您的 HTML 和 JS 中搜索onmousedown处理程序并查找读取的行。

return false;

This line may be stopping you from focusing by clicking.这条线可能会阻止您通过单击来集中注意力。


Re: your comment, I'm assuming you can't edit the code that adds this handler?回复:您的评论,我假设您无法编辑添加此处理程序的代码? If you can, the simplest solution is to just remove the return false;如果可以,最简单的解决方案是删除return false; statement.声明。

is there a way to just add functionality to the event-trigger by not overwriting it?有没有办法通过不覆盖它来向事件触发器添加功能?

That depends on how the handler is attached.这取决于处理程序的附加方式。 If it's attached using the traditional registration method, eg element.onmousedown , then you could create a wrapper for it:如果它使用传统的注册方法附加,例如element.onmousedown ,那么您可以为其创建一个包装器:

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

Since this "wrapper" doesn't return false , it will not cancel the default action (focusing) for the element.由于这个“包装器”不返回false ,它不会取消元素的默认操作(聚焦)。 If your event is attached using an advanced registration method, such as addEventListener or attachEvent then you could only remove the event handler using the function name/reference and reattach it with a wrapped function similar to the above.如果您的事件是使用高级注册方法(例如addEventListenerattachEvent )附加的,那么您只能使用函数名称/引用删除事件处理程序,并使用与上述类似的包装函数重新附加它。 If it's an anonymous function that's added and you can't get a reference to it, then the only solution would be to attach another event handler and focus the element manually using the element.focus() method.如果它是添加的匿名函数并且您无法获得对它的引用,那么唯一的解决方案是附加另一个事件处理程序并使用element.focus()方法手动聚焦元素。

I had this problem too.我也有这个问题。 I used the disableSelection() method of jQuery UI on a parent DIV which contained my input fields.我在包含我的输入字段的父 DIV 上使用了 jQuery UI 的disableSelection()方法。 In Chrome the input fields were not affected but in Firefox the inputs (and textareas as well) did not get focused on clicking.在 Chrome 中,输入字段不受影响,但在 Firefox 中,输入(以及文本区域)没有专注于点击。 The strange thing here was, that the click event on these inputs worked.奇怪的是,这些输入上的点击事件有效。

The solution was to remove the disableSelection() method for the parent DIV.解决方案是删除父 DIV 的disableSelection()方法。

对输入标签使用onclick="this.select()"属性。

I know this is a very old thread, but this just happened to me recently;我知道这是一个非常古老的线程,但这只是最近发生在我身上; took me a while to figure it out.我花了一段时间才弄明白。

This same issue can be caused by putting 'input' elements inside of pair of 'label' tags.将“输入”元素放在一对“标签”标签内可能会导致同样的问题。

In my case, I had intended to create a pair of 'div' tags but instead I accidently created a pair of 'label' tags, then inserted some text input fields 'input type="text"..' using DOM.就我而言,我本来打算创建一对“div”标签,但我不小心创建了一对“标签”标签,然后使用 DOM 插入了一些文本输入字段“input type="text"..”。

It displayed normally on the screen, but when I clicked on any of the text fields, the cursor kept jumping back to the first 'input' and really acting erratic.它在屏幕上正常显示,但是当我单击任何文本字段时,光标一直跳回到第一个“输入”并且表现得很不稳定。

Took me a while to figure this out because this behavior is subtle, and not at all what I would have expected from making this kind of mistake.我花了一段时间才弄清楚这一点,因为这种行为很微妙,而且完全不是我所期望的犯这种错误。

bsnider斯奈德

I've been struggling with the same problem a while ago.不久前我一直在为同样的问题苦苦挣扎。 I was using the jquery.layout plugin in a modal jquery-ui dialog and I couldn't access any of the fields in it.我在模态 jquery-ui 对话框中使用 jquery.layout 插件,但无法访问其中的任何字段。

It appeared to be a z-index problem (some div was over my input fields, so I couldn't click them).这似乎是一个z-index问题(某些div位于我的输入字段上,因此我无法单击它们)。 You should check it out and try changing the z-index value of your input fields.您应该检查一下并尝试更改输入字段的z-index值。

当表单中存在不平衡的<label>标签时,有时会发生这种情况。

我也有这个问题,就我而言,我发现字体的颜色与背景的颜色相同,所以看起来什么也没发生。

This can occur in bootstrap if you do not place your columns inside a <div class ='row'> .如果您没有将列放在<div class ='row'>这可能会在引导程序中发生。 The column floats are not cleared and you could get the next column overlying the previous, hence clicks wont hit the dom elements where you expect.列浮动不会被清除,您可以将下一列覆盖在前一列上,因此点击不会击中您期望的 dom 元素。

If you are faced this problem while using canvas with DOM on mobile devices, the answer of Ashwin G worked for me perfectly, but I did it through javascript如果您在移动设备上使用带有 DOM 的画布时遇到这个问题, Ashwin G的答案对我来说非常有用,但我是通过 javascript 做到的

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

After, everything worked flawlessly.之后,一切都完美无缺。

I have read all the answers above, and some directed me to the problem, but not to the solution for the problem.我已经阅读了上面的所有答案,有些是针对问题的,但不是针对问题的解决方案。

The root cause of the problem is disableSelection() .问题的根本原因是disableSelection() It is causing all the problems, but removing it is not a solution, as (at least in 2016 or slightly before), on touch-screen devices , you "have" to use this if you want to be able to move objects with jQuery.它导致了所有问题,但删除它不是解决方案,因为(至少在 2016 年或稍早之前),在触摸屏设备上,如果您希望能够使用 jQuery 移动对象,则“必须”使用它.

The solution was to leave the disableSelection() to the sortable element, but also add a binding action just above:解决方案是将disableSelection()留给 sortable 元素,但还要在上面添加一个绑定操作:

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

The form in the jQuery element is just to stop propagation on the form, as you might need propagation on some elements. jQuery 元素中的form只是为了停止在表单上传播,因为您可能需要对某些元素进行传播。

I had the similar issue - could not figure out what was the reason, but I fixed it using following code.我遇到了类似的问题 - 无法弄清楚是什么原因,但我使用以下代码修复了它。 Somehow it could not focus only the blank inputs:不知何故,它不能只关注空白输入:

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

I had this problem because of this code:由于此代码,我遇到了这个问题:

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

I resolved it by removing我通过删除解决了它

e.preventDefault(); e.preventDefault();

New code:新代码:

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

Just in case someone else is looking for this answer, we had a similar problem and solved it by changing the z-index of the input tags.以防万一其他人正在寻找这个答案,我们遇到了类似的问题,并通过更改输入标签的 z-index 解决了它。 Apparently some other divs had extended too far and were overlapping the input boxes.显然,其他一些 div 扩展得太远并且与输入框重叠。

I had this problem for over 6 months, it may be the same issue.我有这个问题超过 6 个月,这可能是同样的问题。 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.非常烦人的问题,尤其是对于 textarea 输入字段。 I have this html that gets populated with 1 out of 100s of forms via Javascript:我有这个 html,它通过 Javascript 填充了 100 个表单中的 1 个:

<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.显然 6 个月前我曾试图使弹出窗口可拖动但失败了,同时破坏了文本输入。 Once I removed draggable="true" it works again!一旦我删除了 draggable="true" 它又可以工作了!

I'm using JQuery UI and Bootstrap so I faced this issue and I think it is a conflict between the two as in normal case the textarea or the input filed is editable by nature but I made this solution after testing all the above answers but none solve the cross browser support for all major browsers , but I solved it and I like to share my solution you can use it on input text and textarea我正在使用JQuery UIBootstrap,所以我遇到了这个问题,我认为这是两者之间的冲突,因为在正常情况下,textarea 或输入文件本质上是可编辑的,但我在测试了上述所有答案后做出了这个解决方案,但没有解决了所有主要浏览器跨浏览器支持,但我解决了它,我喜欢分享我的解决方案,您可以在输入文本和文本区域上使用它

(Tested on Desktop: IE (All Versions), Chrome, Safari, Windows Edge, Firefox, Visual Studio Cordova Ripple Viewer on Windows & Visual Studio Cordova Windows 10 Store App) (在桌面上测试:IE(所有版本)、Chrome、Safari、Windows Edge、Firefox、Windows 上的 Visual Studio Cordova Ripple Viewer 和 Visual Studio Cordova Windows 10 商店应用程序)

(Tested on Mobile: Chrome, Firefox, Android Internet Browser & Visual Studio Cordova App on Android & Visual Studio Cordova Windows 8 + 8.1 + 10 Phone App) (在移动设备上测试:Chrome、Firefox、Android 互联网浏览器和 Visual Studio Cordova 应用程序,Android 和 Visual Studio Cordova Windows 8 + 8.1 + 10 手机应用程序)

This is the HTML Code:这是 HTML 代码:

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

This is The CSS Code:这是 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;
 }        

This Is The JQuery Code On Document Ready这是文档就绪的 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);
        });
    }

You can test it on my web application at www.gahwehsada.com您可以在www.gahwehsada.com上的我的 Web 应用程序上对其进行测试

When you say当你说

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

Is this through viewing your html, the source code of the page, or the DOM?这是通过查看您的 html、页面的源代码还是 DOM 来实现的?

If you inspect the DOM with Chrome or Firefox, then you will be able to see any attributes added to the input fields through javasript, or even an overlaying div如果您使用 Chrome 或 Firefox 检查 DOM,那么您将能够看到通过 javasript 添加到输入字段的任何属性,甚至是覆盖的 div

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 ... /> .我刚刚发现了这个问题的另一个可能原因,一些输入文本框缺少关闭的“/”,所以当正确的形式是<input ... />时,我有<input ...> <input ... /> That fixed it for me.那为我修好了。

In my case it was Bootstrap popup in opened state.在我的情况下,它是处于打开状态的 Bootstrap 弹出窗口。 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.文本输入位于 Bootstrap 顶部的另一个日历弹出窗口中,在从 Bootstrap 模式中删除tabindex="-1"属性后,输入重新获得焦点。

iPhone6 chrome iPhone6 镀铬

Problem for me was placing the input field inside <label> and <p>我的问题是将输入字段放在<label><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检查此答案后,请检查此页面中的其他答案,此问题可能有不同的原因

For Anyone Using Electron对于任何使用电子的人

For anyone having this issue with Electron specifically, the problem for me was using alert before selecting the input fields.对于任何在 Electron 上遇到此问题的人,我的问题是在选择输入字段之前使用alert Apparently alert and confirm aren't entirely supported by Electron, and therefore can mess up input fields.显然,Electron 并不完全支持alertconfirm ,因此可能会弄乱输入字段。 If you'd still like to use them, refer to this post: https://stackoverflow.com/a/38859135/12293837如果您仍想使用它们,请参阅此帖子: https : //stackoverflow.com/a/38859135/12293837

This will also happen anytime a div ends up positioned over controls in another div;这也会发生在一个 div 最终定位在另一个 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.就像使用引导程序进行布局,并有一个“col-lg-4”后跟一个“col-lg=8”拼写错误......右侧孤立/错误命名的div覆盖左侧,并捕获鼠标事件。 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.因此,付费与检查员一起检查并寻找“惊喜”以发现这些疯狂的 div。

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...事实证明,fatfingering = for - 使用引导类名是一种方法......

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.当我这样做时,我发现有一个 z-index 为 9999 的隐藏元素,一旦我修复了我的问题就消失了。

the problem for me was that I was using class="modal fade" , I changed it for class="modal hide" .我的问题是我使用的是class="modal fade" ,我将其更改为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原来是一个未封闭标签。尝试验证您的 HTML 代码,解决方案可能是未封闭的标签导致问题

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.我在使用 Bootstrap + 联系表 7 时遇到了这个问题。出于某种原因,我将标签作为表单的容器,这是无法在移动设备上选择的问题。

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

Seemed to break all inputs except the first input and the submit.似乎破坏了除第一个输入和提交之外的所有输入。

我遇到了同样的问题,解决方法是删除占位符,我更改了表单的设计以使用标签而不是占位符...

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.我有这个问题是由于div元素与 bootstrap class ="row"重叠在class="col"的“兄弟” div元素上,第一个隐藏了第二个div元素的焦点。

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.我解决了从 div 树的那个级别取出div row元素的问题,因此根据rowcol类重新平衡引导程序逻辑层次结构。

I had this same issue just now in React.我刚才在 React 中遇到了同样的问题。

I figured out that in the Router, Route.我在路由器中发现了这一点,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丹尼尔

值得补充的是,输入标签上的属性pointer-events:none也会产生这种不需要的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM