【发布时间】:2022-12-07 16:23:39
【问题描述】:
我在顶部导航栏中有一个搜索按钮。当用户单击时,将打开一个带有文本输入字段的模式。当模式打开时,我希望键盘焦点自动位于文本输入字段内。
这是搜索模式代码:
<div class="modal" id="searchModal" tabindex="1" aria-labelledby="searchModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="searchModalLabel">Search parks</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<%= search_form_for @q, url: :parks do |f| %>
<%= f.hidden_field :has_entrance_fee_eq %>
<%= f.hidden_field :region_eq %>
<div class="form-group">
<%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
autofocus: true,
placeholder: "Search for a park (English or Hebrew)",
class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit 'Search parks', name: "", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
</div>
</div>
我已经尝试过在 rails 表单中简单地添加 autofocus: true,但它不起作用:
<div class="form-group">
<%= f.text_field :name_en_or_name_he_or_description_en_or_description_he_cont,
autofocus: true,
placeholder: "Search for a park (English or Hebrew)",
class: "form-control" %>
</div>
Bootstrap 文档说:
由于 HTML5 定义其语义的方式,autofocus HTML 属性在 Bootstrap 模态中无效。要达到相同的效果,请使用一些自定义 JavaScript:
var myModal = document.getElementById('myModal') var myInput = document.getElementById('myInput') myModal.addEventListener('shown.bs.modal', function () { myInput.focus() })但我不太熟悉 Javascript,所以不确定在哪里/如何使用这段代码,如果这确实是正确的方向……总的来说,我是编码新手,所以任何帮助将不胜感激,越具体更好的!
【问题讨论】:
标签: javascript bootstrap-modal focus bootstrap-5 ruby-on-rails-7