我的目标是:
- 当用户点击按钮时显示弹出窗口
- 当用户点击别处时隐藏弹窗
我试过这个解决方案,效果很好:Use jQuery to hide a DIV when the user clicks outside of it
但我想尝试一些不同的东西,我想尝试 focus()
所以我写了这段代码:
div
{
width: 100px;
height: 100px;
border: 1px solid blue;
}
div:focus
{
background-color: red;
}
<script>
function show()
{
document.getElementById("element").focus();
}
</script>
<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">
</div>
After you clicked the button, click elsewhere to remove the red background
效果很好,现在我想隐藏 block 并在用户单击按钮时显示它,我刚刚添加了 display: block
和 display: none
,这是两个版本之间的唯一区别
div
{
width: 100px;
height: 100px;
border: 1px solid blue;
display: none;
}
div:focus
{
background-color: red;
display: block;
}
<script>
function show()
{
document.getElementById("element").focus();
}
</script>
<input type="button" onclick="show()" value="click me!"/>
<div id="element"tabindex="-1">
</div>
它不再工作了,有人能告诉我为什么吗?
最佳答案
您不能聚焦应用了 display: none
的对象。
来自 this question :
Elements that are not visible cannot receive focus, therefore the :focus psuedo-class cannot apply.
关于javascript - 使用 focus() 显示 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47189686/