怎么使弹出窗口溢出:在溢出内可见:自动上下文

本教程将介绍如何使弹出窗口溢出:在溢出内可见:自动上下文的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么使弹出窗口溢出:在溢出内可见:自动上下文 教程 第1张

问题描述

我有一个div列表(如果超出父框,则应滚动overflow-x),并且在悬停时,我希望看到弹出窗口。

我的问题是,如果我悬停任何子div,溢出计算都会考虑弹出窗口,但我只想让它在所有内容的顶部可见,而不是使它扩展滚动区域,也不希望它隐藏在父div的右边界上。我可以以某种方式将其从父/子上下文中分离吗?

.parent {overflow-x: visible}不是一个选项,因为我希望保持父对象的大小,并使子对象可滚动。

div {
  border-style: solid;
  margin: 10px;
}

.parent {
  overflow-x: auto;
  white-space : nowrap;
  width: 200px;
  height: 150px;
  background-color: grey;
}

.child {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 100px;
  background-color: lightblue;
}

.popover {
  display: none;
  position: absolute;
  left: 30px;
  z-index:9999;
  width: 80px;
  height: 50px;
  background-color: lightgreen;
}

.child:hover .popover {
  display: block;
}
<div class="parent">
  <div class="child">
 <div class="popover">
 </div>
  </div
  ><div class="child">
 <div class="popover">
 </div>
  </div
  ><div class="child">
 <div class="popover">
 </div>
  </div>
</div>

推荐答案

IMHO只要弹出窗口位于带有&quot;overflow:auto&quot;、&quot;overflow:scroll&quot;或&quot;overflow:idden&quot;的div中,您就无法避免使用纯HTMLcss/css试图避免的行为。不过,请找个人帮我纠正一下。

我建议按照我的示例使用最小的JS(JQuery)。这也可以用香草JS来完成,但是我觉得不值得这么做。
基本上,JS做三件事,(1)附加到Mouseenter和Mouseleave事件,(2)在捕获和冒泡阶段停止事件的进一步传播,(3)设置弹出窗口的位置。

这还有一个额外的好处,即可以控制弹出窗口的其他各个方面。

出于完整性考虑,我也创建了一个普通的JS版本,尽管我不会这样做。

$(".child").on( {
 mouseenter: function(event) {
  event.stopPropagation();
  let position = $(this).offset();
  $(this).find(".popover").css("top", position.top);
  $(this).find(".popover").css("left", position.left-10);
  $(this).find(".popover").css("display", "block");
 },
 mouseleave: function(event) {
  event.stopPropagation();
  $(this).find(".popover").css("display", "none");
 }
});
div {
  border-style: solid;
  margin: 10px;
}

.parent {
  overflow-x: auto;
  white-space : nowrap;
  width: 200px;
  height: 150px;
  background-color: grey;
}

.child {
  position: relative;
  display: inline-block;
  width: 70px;
  height: 100px;
  background-color: lightblue;
}

.popover {
  display: none;
  position: fixed;
  z-index:9999;
  width: 80px;
  height: 50px;
  background-color: lightgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
  <div class="child">
 <div class="popover">
 </div>
  </div
  ><div class="child">
 <div class="popover">
 </div>
  </div
  ><div class="child">
 <div class="popover">
 </div>
  </div>
</div>

好了关于怎么使弹出窗口溢出:在溢出内可见:自动上下文的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。