【问题标题】:overflow:scroll div with position:absolute element inside溢出:滚动 div 与位置:内部绝对元素
【发布时间】:2018-02-09 22:35:13
【问题描述】:
我在溢出:滚动容器中有一个表格,表格中有一些按钮,当有人单击它们时,它们会显示上下文/工具提示(位置:绝对层)文本。
当我向右滚动并单击按钮时,它会向右移动而忽略滚动:
使容器位置相对解决了位置问题,但它出现在容器内没有显示菜单:
我需要帮助才能获得以下所需行为:
这是sn-p:
.container{
width:200px;
height:100px;
overflow:scroll;
position:relative; /* removing this solves the problem, but .contextual moves to the original position */
}
.board{
width:400px;
}
.contextual{
display:none;
position:absolute;
width:100px;
height:100px;
margin: 20px;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=container>
<table class=board>
<tr><td colspan=2>This board size (200) is bigger than its container size (100).</td></tr>
<tr>
<td>this is a button with a contextual element</td>
<td>
<input type=button value="click me" onclick="$('.contextual').show();" />
<div class=contextual>This is a contextual help text.</div>
</td>
</tr>
</table>
</div>
【问题讨论】:
标签:
css
scroll
css-position
absolute
【解决方案1】:
对于有此问题但设置为鼠标位置无济于事的人
如果你和我有同样的问题,父容器设置为overflow: scroll,尽管position: absolute,父容器的子元素被切断 - 执行以下操作
例如用例,构建下拉菜单
- 将元素设置为
position: fixed
- 获取父元素的视口位置
- 将位置
top、left、bottom、right 值设置为视口值
您可以使用与来自@jfeferman 的代码 sn-p 相同的代码
【解决方案2】:
将上下文 div 放在溢出的 div 之外,并根据鼠标位置定位。
showContext = function() {
var e = window.event;
var posX = e.clientX;
var posY = e.clientY;
var context = document.getElementById("contextual")
context.style.top = posY + "px";
context.style.left = posX + "px";
context.style.display = "block";
}
.container{
width:200px;
height:100px;
overflow:scroll;
position:relative; /* removing this solves the problem, but .contextual moves to the original position */
z-index:1;
}
.board{
width:400px;
}
#contextual{
display:none;
position:absolute;
width:100px;
height:100px;
background-color:grey;
z-index: 2;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table class="board">
<tr><td colspan=2>This board size (200) is bigger than its container size (100).</td></tr>
<tr>
<td>this is a button with a contextual element</td>
<td>
<input type="button" value="click me" onclick="javascript:showContext();" />
</td>
</tr>
</table>
</div>
<div id="contextual">This is a contextual help text.</div>
【解决方案3】:
您可以使用overflow: auto。这将仅在必要时显示滚动条。此外,您可以从.contextual 中删除z-index: 2。