gpt4 book ai didi

Javascript - 关闭模态后聚焦于元素

转载 作者:行者123 更新时间:2023-12-03 00:51:52 25 4
gpt4 key购买 nike

我有一个带有自动对焦属性的按钮。当用户单击按钮(或按“输入键”,因为它具有自动对焦功能)时,会弹出一个模式。该模式还有一个带有自动对焦属性的输入字段。用户在其中输入内容并按“回车键”后,模式将关闭。

我希望在关闭模式后再次聚焦初始按钮。但我无法让它发挥作用。

我尝试将 autofocus 属性添加到按钮本身,并且还尝试将 document.getElementById("myBtn").focus(); 添加到该函数关闭模态框。没有一个起作用。

我尝试替换按钮的输入字段来关闭模式,它就是这样工作的,所以我猜问题与 onKeyDown="if(event.keyCode==13) closeModal( ); 在输入中,因为“回车键”在页面中用于不止一件事。

我的假设正确吗?有没有办法让它在这些条件下工作?

这是我正在使用的简化版本:

var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");
btn.onclick = function() {
modal.style.display = "block";
document.getElementById("modalInput").focus();
}

function closeModal() {
modal.style.display = "none";
document.getElementById("myBtn").focus();
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 200px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}

.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
width: 30%;
text-align: center;
}
<button id="myBtn" autofocus>Open Modal</button>

<div id="myModal" class="modal">
<div class="modal-content">
<p>This is a modal.</p>
<input id="modalInput" type="text" autofocus onKeyDown="if(event.keyCode==13) closeModal();">
</div>
</div>

最佳答案

当您使用输入标签按下回车键时,会同时调用聚焦按钮。这会立即触发按钮上的 Enter 键事件。

这样模态似乎没有关闭。输入 setTimeout 将修复它。您可能需要使用 :focus 伪类选择器对其进行样式设置,以将其显示为聚焦。

var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");
btn.onclick = function() {
modal.style.display = "block";
document.getElementById("modalInput").focus();
}

function closeModal() {
modal.style.display = "none";
setTimeout(function(){
document.getElementById("myBtn").focus();
},0)
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 200px;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}

.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
width: 30%;
text-align: center;
}
<button id="myBtn" autofocus>Open Modal</button>

<div id="myModal" class="modal">
<div class="modal-content">
<p>This is a modal.</p>
<input id="modalInput" type="text" autofocus onKeyDown="if(event.keyCode==13) closeModal();">
</div>
</div>

关于Javascript - 关闭模态后聚焦于元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com