让我们想象一下两列视图。在左栏中,您有城市名称,在右侧列中,有属于这些城市的国家/地区。每个国家都在自己的div。
---------------------- ---------------------- <div>
Berlin
________________________________________________ Screen Top
Freiburg ----------- Germany
Göttingen
Hamburg
Hannover
München
________________________________________________ Screen Bottom
Xanten
---------------------- ---------------------- </div>
从上面的草稿中可以看出,右栏的div中有更多条目。城市数量如此之大,以至于它们不适合一个屏幕。我现在希望将国家视为第二列的第一行,只要显示相应的城市名称即可。如果我继续滚动并显示下一个国家的第一个城市,则应按其国家/地区名称进行交换。因此,div的结束点和起点需要同步,但可能存在大量的div。
有什么想法吗?
答案 0 :(得分:1)
我提出的解决方案是this小提琴。
它的工作方式是您使用class='item'
每种格式都有以下格式:
<div class="item">
<div class="left">
City 1 <br/>
City 2 <br/>
City 3 <br/>
...
</div>
<div class="right">
Country Name
</div>
</div> <!-- end item -->
每个国家/地区都有自己的item
div,其中包含城市和国家/地区名称。
<强> CSS:强>
.item {
width: 100%;
float: left;
position: relative;
margin-bottom: 5px;
}
.left, .right {
width: 50%;
float: left;
}
.right {
position: absolute;
right: 0px;
top: 0px;
}
<强> JavaScript的:强>
var curChild = 1; // Which country is currently top of the parent div
$('.main').scroll(function () {
// curChildBottom is the location of the bottom of curChild, with
// respect to the top of the parent div
var curChildBottom = $('.main .item:nth-child(' + curChild + ')').position().top + $('.main .item:nth-child(' + curChild + ')').height();
// scrollStop is the location at which the country name no longer moves
var scrollStop = curChildBottom - $('.main .item:nth-child(' + curChild + ') .right').height();
// scrollValue is the current scroll bar position
// Note: negative because .position().top gives a negative value when scrolled up
var scrollValue = -($('.main .item:nth-child(' + curChild + ')').position().top - 1);
// If .right has reached the bottom of .item
if (scrollStop < 0) {
$('.main .item:nth-child(' + curChild + ') .right').css('top', 'auto');
$('.main .item:nth-child(' + curChild + ') .right').css('bottom', '0px');
// If the current child is no longer visible within parent div
if (curChildBottom <= 0) {
curChild++;
}
} else {
$('.main .item:nth-child(' + curChild + ') .right').css('bottom', 'auto');
$('.main .item:nth-child(' + curChild + ') .right').css('top', scrollValue);
if (scrollValue < 0) {
$('.main .item:nth-child(' + curChild + ') .right').css('bottom', 'auto');
$('.main .item:nth-child(' + curChild + ') .right').css('top', '0px');
if (curChild > 1) {
curChild--;
}
}
}
});
该脚本通过更改right
div的位置来工作,该位置在其父div(视图fiddle)中具有绝对位置。请注意,.item
必须有position: relative;
作为CSS属性。