gpt4 book ai didi

html - 使用比例响应 div 调整页面大小时保持查看位置

转载 作者:行者123 更新时间:2023-11-28 03:19:59 24 4
gpt4 key购买 nike

我有一堆 100% 宽度的 div,它们在调整浏览器窗口大小时保持它们的形状/比例。我的问题是:如果我向下滚动到底部的 div(本例中为黄色),然后我调整浏览器窗口的大小,我最终会看到一个不同的 div,因为它们保持着它们的比例。请问有办法阻止吗?

http://jsfiddle.net/nWrVY/

CSS:

.wrapper {
width: 100%;
display: inline-block;
position: relative;
}
.wrapper:after {
padding-top: 161.8%;
display: block;
content:'';
}

HTML:

<body>
<div class="wrapper" style="background-color: red;"></div>
<div class="wrapper" style="background-color: black;"></div>
<div class="wrapper" style="background-color: green;"></div>
<div class="wrapper" style="background-color: yellow;"></div>
</body>

最佳答案

您可以通过几个步骤在 javascript 中解决这个问题。

var current = "";

function scroll(){
// add 20 pixels to the scroll top so after we scrolled it does't fallback to the div before the one we're actually at.
var scrolltop = $(document).scrollTop() + 20;
$(".wrapper").each(function(){
// check if the offset of all divs is smaller than the scroll top
// the last one found is the last one visible
// save that one to a global variable so the resize function an access it
if($(this).offset().top < scrolltop) current = $(this);
})
}

function resize(){
// here we apply the top of the div to the body as scroll top
$("body").stop().animate({scrollTop:current.offset().top+"px"});
}

$(window).resize(resize);
$(document).scroll(scroll);

[编辑] 我修改了代码以使其更准确(我在滚动顶部添加了 20 个像素,因此当前元素的重新定义不会将其重新定义为它上方的元素)。这需要 jQuery,所以添加

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

对于您的部分,这应该有效,我在 fiddle 上对其进行了测试。

关于html - 使用比例响应 div 调整页面大小时保持查看位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24996888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com