javascript - 当用户使用 jQuery 滚动时,在不同的 div 中触发滚动事件
问题描述
我有两个 div 元素:
当用户滚动 div#element-A
并#header-one-target
到达包含 div 的顶部时,最后一个元素 ( #animate-hd-b
)#element-B
应该滚动到包含 div 的顶部,并带有漂亮的动画。
这是我开始使用的代码。下面的代码在滚动窗口而不是 div 时执行某些操作。
$(window).scroll(function() {
var offsetTop = $('#animate-hd-b').offset().top,
outerHeight = $('#animate-hd-b').outerHeight(),
windowHeight = $(window).height(),
scrollTop = $(this).scrollTop();
console.log((offsetTop-windowHeight) , scrollTop);
if (scrollTop > (offsetTop+outerHeight-windowHeight)){
alert('you have scrolled to the top!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element-A" style="background: orange; overflow: auto;">
<div class="content" style="padding-bottom: 300px;">
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<h1 id="header-one-target">Header One</h1>
</div>
</div>
<div id="element-B" style="background: yellow; overflow: auto;">
<div class="content" style="padding-bottom: 300px;">
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<h1 id="animate-hd-b">Animate This Header</h1>
</div>
</div>
有没有办法在 jQuery 中做到这一点?
解决方案
这真的很简单。您只需在到达顶部时跟踪#header-one-target
并设置动画
。#animate-hd-b
#header-one-target
(function($) {
let $elementA = $('#element-A');
let $elementB = $('#element-B');
let $headerOneTarget = $('#header-one-target');
let $animateHdB = $('#animate-hd-b');
let isScrollAtTop = true;
$elementA.scroll(function() {
if (isScrollAtTop && $headerOneTarget.offset().top < 5) {
isScrollAtTop = false;
$elementB.animate({
scrollTop: $elementB.scrollTop() + $animateHdB.offset().top
});
} else if ($elementA.scrollTop() < 5) {
isScrollAtTop = true;
$elementB.animate({
scrollTop: 0
});
}
});
})(jQuery);
#element-A {
background: orange;
overflow: auto;
height: 100vh;
width: 60vw;
position: fixed;
top: 0;
left: 0;
}
#element-B {
position: fixed;
top: 0;
right: 0;
height: 100vh;
width: 40vw;
background: yellow;
overflow: auto;
}
.content {
padding: 10px;
}
.content-vh100 {
height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element-A">
<div class="content">
<p>Scroll</p>
<p>to</p>
<p>header</p>
<p>one</p>
<h1 id="header-one-target">Header One</h1>
<div class="content-vh100"></div>
</div>
</div>
<div id="element-B">
<div class="content">
<p>to</p>
<p>animate</p>
<p>following</p>
<p>content</p>
<h1 id="animate-hd-b">Animate This Header</h1>
<div class="content-vh100"></div>
</div>
</div>
推荐阅读
- ethereum - 每次购买的最大代币价值 - BSC - Solidity
- java - 权限 PROCESS_OUTGOING_CALLS 用于检测被 Android 拒绝的拨出电话
- javascript - 比较javascript中的两个日期对象
- ansible - 在ansible任务中引用字典变量值
- reactjs - 不支持扩展 create-react-app 获取 src/ 之外的相对导入
- python - 如何将 Stanza Word 标记化数据保存在单个 CSV 文件中?
- javascript - 如何在 javascript 中存储玩家猜测并检查字母字符
- ubuntu - 如何连接到使用 vmwares vmrun CLI 命令启动的虚拟机的 GUI?
- c# - 如何为不和谐机器人编写单元测试
- spring-boot - 使用 String 时 MockMVC @PathVariable 不起作用