我有以下示例中的模态表单:
<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
Enter something: <input type="text" id="myInput">
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
我希望我的输入字段在模式显示后得到关注。
我已经尝试了自动聚焦和在$('modal').shown()
事件上设置字段焦点。它有点聚焦字段(我有另一个事件,当字段被聚焦时会显示标签),但实际上字段并不是聚焦的,我必须再次按TAB
来聚焦它。我也尝试了类似这样的东西:
$(".modal").on('shown', function() {
$(this).find("[autofocus]:first").focus();
});
并为我的字段设置autofocus:"autofocus"
属性。它产生了同样的效果。
当modal只是一个普通的div时,我尝试过的所有东西都是有效的,它得到了页面加载的关注。但是当modal被按钮触发时--什么都不起作用(当然我也改变了逻辑,当modal只是一个普通的div时,我可以将它集中在onload上,当我通过按钮触发时,我会考虑到它,并尝试相应地解决它)。
我想要的只是领域后,模式被加载,以便它有闪烁的光标和用户可以开始键入。
唯一起作用的是改变bootstrap.js本身,我把$("#myInput").focus()
放在bootstrap.js模式部分的某个地方,但是我忘了它在哪里,第二,我认为改变bootstrap.js接口不好,必须有更简单、更优雅的解决方案。请给我建议,谢谢xD
更新:
首先,感谢您的帮助!多亏了你,我才发现我的问题就是Rails的问题。
下面是我所做的:
1)。rails generate controller home index
2)。app/views/home/index.html和app/assets/javascript/omething.js类似于robertklep提供的这个jsFiddle:http://jsfiddle.net/JCaFp/
4)。jquery-1.9.1.js和bootstrap.js在app/assets/javascript/中(两者都是从网站上新来的,没有什么变化)
5)。app/views/layout/application.html.erb-我想这个文件是我们解决方案的关键:
<!DOCTYPE html>
<html>
<head>
<title>Udc</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<%= yield %>
</body>
</html>
还是不管用。所有的js文件都包含在内,但是当我在browser - input中打开我的模式时,会获得一段时间的焦点,然后再次变得没有焦点。
我也尝试过这个:
<%= javascript_include_tag "jquery" %>
<%= javascript_include_tag "bootstrap" %>
<%= javascript_include_tag "somehow" %>
还是一样的东西。
建议?:)
更新:
解决了这个问题!
将我的somehow.js
更改为
$(document).ready(function() {
$(".modal").on('shown', function() {
$(this).find("[autofocus]:first").focus();
});
});
和application.html.erb
样式表:
<%= javascript_include_tag "jquery" %>
<%= javascript_include_tag "bootstrap" %>
<%= javascript_include_tag "somehow" %>
它的工作方式与预期一致。再次感谢!
发布于 2013-12-17 16:44:45
发布于 2014-05-10 02:26:30
对于不需要为每个对话框指定特定代码的一般解决方案,您可以使用以下代码:
$('.modal').on('shown.bs.modal', function () {
$(this).find('input:text:visible:first').focus();
})
发布于 2015-02-12 14:49:08
尝试删除tabindex="-1"
,效果很好。
因此,请更改以下内容:
<div class="modal fade" id="modalID" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
要这样做:
<div class="modal fade" id="modalID" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
https://stackoverflow.com/questions/15474862
复制相似问题