javascript - 使用 focus() 显示 block

标签 javascript html css

我的目标是:

  • 当用户点击按钮时显示弹出窗口
  • 当用户点击别处时隐藏弹窗

我试过这个解决方案,效果很好: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: blockdisplay: 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/

相关文章:

javascript - Contenttools - 通过 jQuery 附加数据

html - 网站在大视口(viewport)上看起来不错,但在小屏幕上质量会受到影响

php - Wordpress query_posts() 不显示旧帖子

javascript - 无论先前的元素长度如何,如何将 anchor 对齐到中心

javascript - 匹配某个字符之前的所有内容并匹配某个字符之后的所有内容

javascript - meteor /蒙戈 : Get object of nested array to a template spacebar

javascript - 检测视频分辨率变化

html - 浏览器高度为 100% 的静态和流动列

html - 尝试为背景图像添加透明度不透明度

javascript - ajax表中的排序函数