在一个overflow-y: scroll的div中定位绝对定位的div

8

我有如下HTML:

<div class="container">
<div class="scrollable-block">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    <div class="absolute-div"></div>
</div>

同时还有CSS:

.container {
    width: 200px;
    height: 300px;
    background: green;
}

.scrollable-block {
    width: 200px;
    max-height: 250px;
    overflow: scroll;
    position: relative;
}

.absolute-div {
    width: 20px;
    height: 20px;
    background: purple;
    position: absolute;
    top: 0;
    right: -10px;
}

在这里有一个实时演示:http://jsfiddle.net/BYTam/1/ 绿色的 div 是容器,具有固定的宽度。黄色的 div 在其中并具有最大高度和 overflow-y: scroll 属性。它应该与绿色的 div 具有相同的宽度。我正在尝试绝对定位紫色的 div,相对于黄色的 div,但在绿色的 div 外部 - 原因是我不希望黄色的 div 有水平滚动条。这是否可能?
谢谢!

也许你可以在 .container 上加上 position: relative,而不是在 .scrollable-block 上加?这样可以吗? - Vladislav Stanic
不,不幸的是它需要相对于.scrollable-block。这只是一个更复杂结构的被压缩示例,需要以这种方式运作。 - Yavor Punchev
3个回答

2

你无法使用当前的标记完成它。absolute-div总是会触发水平滚动条,因为它嵌套在可滚动块内。似乎现代浏览器不允许同时使用overflow-x:visible和overflow-y:scroll。


有没有办法让绝对定位的 div 超出容器 div?Z-index 似乎不起作用。 - Yavor Punchev
@YavorPunchev - 如果不改变HTML(或使用JavaScript更改HTML / DOM),则无法实现。 - Louis Ricci

1

我认为不可能让绝对定位的 div 超出滚动块。我也遇到了同样的问题,以下是我的解决方法:

 <div class="absolute-div"></div> // replace it, put it in the main container.

 $(".absolute-div").css({"top":play with this+"px"}); 
// on scroll of the "scrollable-block" change the ".absolute-div" "top" property using Jquery.

-1
如果您不想要水平滚动条,只需将overflow:scroll更改为
overflow-y:scroll;
overflow-x:hidden;

1
是的,但这样绝对定位(紫色)的 div 仍然保持隐藏。 - Yavor Punchev
对我来说,可滚动块的右上角有一个紫色的块,这很奇怪。 - what is sleep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接