简体   繁体   English

通过jQuery添加css:focus selector

[英]Add css :focus selector via jQuery

I have a Bootstrap modal with a form that is triggered when two buttons on the page are clicked. 我有一个Bootstrap模式,其中包含单击页面上的两个按钮时触发的表单。

When one specific button is clicked, I want a specific input field within the form to be in focus, as in the cursor is in that field and the styling for :focus is applied. 当单击一个特定按钮时,我希望窗体中的特定输入字段处于焦点,就像光标位于该字段中一样,并且应用了样式:focus。

$('.bio-input').focus(); does not seem to work (although it works in the code snippet). 似乎不起作用(尽管它在代码片段中有效)。 Even though this element I'm trying to bring into focus is in a modal, the modal is rendered on page load as a partial, so the element is available in the DOM on click. 尽管我试图引起关注的这个元素是一个模态,但是模态在页面加载时呈现为部分,因此该元素在点击时在DOM中可用。

At the bottom of my view (slim), I have the partial that holds the modal: 在我的视图底部(苗条),我有部分持有模态:

 = render partial: 'users/profile/edit_profile_modal'

The modal has an id of #popup-editprofile . 模态的id为#popup-editprofile

Then, below, my button tag has that id as the data-target, and the data-toggle is 'modal'. 然后,在下面,我的按钮标记将该id作为数据目标,并且数据切换为“模态”。

Thanks in advance for your help. 在此先感谢您的帮助。

 $(document).ready(function() { $('.edit-bio-btn').click(function() { $("#bio-input").focus(); }) }); 
 #bio-input:focus { border-left: 5px solid orange; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button name="button" type="submit" class="button btn btn-xs edit-bio-btn" data-target="#popup-editprofile" data-toggle="modal"><i class="fa fa-pencil"></i><span>Edit bio</span></button> <textarea name="profile[bio]" id="bio-input" placeholder="Enter Bio" class="form-control edit-profile-input"></textarea> 

You can use the focus() function. 您可以使用focus()函数。 Once the button is clicked, the input field will be focused. 单击按钮后,输入字段将被聚焦。

$('.edit-bio-btn').click(function() {
    $('input.thisClass').focus();
})

DEMO DEMO

Try this: http://jsfiddle.net/mgm1k5s7/ 试试这个: http//jsfiddle.net/mgm1k5s7/

$("#button").on("click", function () {
    $("#input").focus();
});

Bootstrap Modal Events: http://getbootstrap.com/javascript/#modals-events Bootstrap模态事件: http//getbootstrap.com/javascript/#modals-events

After you finally provided the information that you were using a bootstrap modal, the answer becomes clear: 在您最终提供使用引导模式的信息后,答案变得清晰:

$('#id-of-modal-element').on('shown.bs.modal',function() {
  $('.bio-input',this).focus();
});

This snippet says, when your modal element fires the shown.bs.modal event, focus on the .bio-input element that is inside of that modal. 这个片段说,当你的模态元素触发shown.bs.modal事件时,请关注该模态内部的.bio-input元素。

If this doesn't work for you, then you've got to provide a link to your page, or code that reproduces your issue. 如果这对您不起作用,那么您必须提供指向您的页面的链接或代码以重现您的问题。

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

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