javascript - Bootstrap modal 将焦点放在靠近正文输入的弹出窗口上
问题描述
嗨堆栈溢出社区的人
当用户单击引导模式窗口时,我想将焦点设置在输入上。
我尝试了下面的代码但没有帮助。任何帮助表示赞赏。
$('#myModal').on('hidden.bs.modal', function() {
$('#focusMe').focus()
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
<!--CB-modal -->
<!-- Button trigger modal -->
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<label>Foucs Me</label>
<input type="text" id="focusMe">
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- JS code -->
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js">
</script>
解决方案
您只需要setTimeout()
在调用 focus() 事件进行输入之前添加函数。
focus()
在引导模式关闭后立即调用的代码方法中,当DOM
未正确加载时。
$('#myModal').on('hidden.bs.modal', function() {
setTimeout(function(){
$('#focusMe').focus();
},100);
});
推荐阅读
- powerbi - 在 DAX 中使用整个表时性能总是很差吗?
- html - 如何将这两个项目彼此对齐?
- asp.net - 将图像显示为链接
- javascript - HTML 元素未在 Gatsby 网站上呈现
- python - 具有索引、约束和权限的 Django 抽象模型:属性不被子类继承
- java - Java JPA with DiscriminatorColumn
- c++ - 构建没有依赖关系的 c++ exe
- flutter - 如何从另一个类调用 SetState
- java - Selenium:切换到下一个文档以读取 excel 时出现“StaleElementReferenceException”
- c++ - 标准 C++ 中的非空相对当前路径?