gpt4 book ai didi

javascript - JQuery ScrollTop 不滚动到正确的项目

转载 作者:行者123 更新时间:2023-12-03 05:44:07 25 4
gpt4 key购买 nike

我正在尝试滚动到 div 容器内的项目。滚动到顶部功能可以工作,但似乎超出了该项目。

Javascript

<script>
$(document).ready(function () {
var container = $('#directory'),
scrollTo = $('.highlight_bg');
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
}, 2000);
});
</script>

HTML:

<div id="directory" class="directory" style="height: calc(100% - 111px)">
<div class="directoryitem"></div>
<div class="directoryitem"></div>
<div class="directoryitem highlight_bg"></div>
<div class="directoryitem"></div>
</div>

所以最后是滚动到类名为 highlight_bg

的 div 项

不确定哪里出了问题?

最佳答案

您的 Javascript 代码实际上正在运行。那么也许是 CSS 问题?

$(document).ready(function () {
var container = $('#directory'),
scrollTo = $('.highlight_bg');
container.animate({
scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
}, 2000);
});
/* DEMO STYLISING PART */

.directoryitem {
display: block;
height: 90%;
width: 90%;
background-color: #CCC;
border: 5px solid gray;
}
.highlight_bg {
background-color: green;
}

/* SCROLL PART */

html, body {
height: 100%;
width: 100%;
}

.directory {
position: relative;
height: 100%;
width: 100%;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="directory" class="directory" style="height: calc(100% - 111px)">
<div class="directoryitem"></div>
<div class="directoryitem"></div>
<div class="directoryitem highlight_bg"></div>
<div class="directoryitem"></div>
</div>

关于javascript - JQuery ScrollTop 不滚动到正确的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40402240/

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