简体   繁体   English

focus()不适用于锚链接

[英]focus() doesn't work with anchor link

<a id="news_click" href="#news"> <span style="color:#B2B2B2" class="radius secondary label">Do you want fresh news and feeds?</span></a>

<div class="large-5 columns">
    <div class="row collapse">
        <div class="small-12 columns">
            <form id="email_form" data-validate="parsley" data-trigger="focusin focusout">
                </br>
                <input id="email" type="text" placeholder="Email" class="hg" name="email" data-notblank="true" data-type="email">
            </form>
        </div>
    </div>
</div>

<div class="bottom_blue" id="news"></div>

$('#news_click').click(function () {
    $('form#email_form input#email.hg').focus();
});

The focus event only works if i remove the <div class="bottom_blue" id="news"></div . 仅当我删除<div class="bottom_blue" id="news"></div ,焦点事件才起作用。 This is not an option since this is an anchor link. 这不是一个选项,因为这是一个锚链接。

Any idea? 任何想法? Probably the problem is that js is executed before the anchor. 可能的问题是js在锚点之前执行。

EDIT: Apparently this works in chrome, not in FF. 编辑:显然这适用于chrome,而不是FF。

demo 演示

Essentially you need to account for the click event and focus as a race condition in Firefox. 本质上,您需要考虑一下click事件,并将焦点作为Firefox中的竞争条件。 Use either: 使用以下任一方法:

$('#news_click').click(function (e) {
    e.preventDefault();
    $('#email').focus();
});

or 要么

$('#news_click').click(function (e) {
    setTimeout(function(){$('#email').focus();},10);
});

jsFiddle example jsFiddle示例

You forgot an angle bracket at the end of <div class="bottom_blue" id="news"></div ... 您忘记了<div class="bottom_blue" id="news"></div ...末尾的尖括号...

Demo here 在这里演示

Use this instead: 使用此代替:

<div class="bottom_blue" id="news"></div>

Also, try changing this: 另外,尝试更改此设置:

$('form#email_form input#email.hg').focus();

To this: 对此:

$('#email').focus();

There can only be one element with the same id anyway, so it makes no difference how specific you are. 无论如何,只能有一个具有相同id元素,因此您的具体程度没有区别。

EDIT: Firefox seems to visit the href after the email box is focused... You can either use preventDefault() as in j08691's answer, or take the href attribute off the link (see the updated fiddle ). 编辑: Firefox似乎在聚焦email框之后访问了href ...您可以按照j08691的答案使用preventDefault() ,也可以将href属性从链接中移除(请参阅更新的小提琴 )。

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

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