运用onscroll事件//滚动窗口滚动条时触发

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>day08_作业讲解</title>
<style>
body{margin: 0;height:2000px;}
header{
height: 60px;
background: #f00;
}
.toolbar{height:300px;border: 1px solid #000;}
.fixed{position: fixed;top: 0;left: 0;right: 0;}
</style>
<script>
//页面加载时间
window.onload =function(){
//顶部悬浮(吸顶菜单)
//1)获取元素
var topNav = document.getElementById("topNav");
//2)当滚动到指定位置是给#topNav添加fixed类
//绑定滚动事件 (gunlun/拖动滚动条)时执行函数中的代码
window.onscroll = function(){
//console.log('1111');

//获取滚动条滚动过的距离
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

// 当滚动到<指定位置>时给#topNav添加fixed类
if(scrollTop >= 302){
//给元素添加类:ele.className = 'xx';
topNav.className = 'fixed';
}else{
topNav.className = '';
}

}



}
</script>
</head>
<body>
<div class="toolbar"></div>
<header id="topNav"></header>
</body>
</html>

转载于:https://www.cnblogs.com/R-jia-bao/p/6143011.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Vue3中,你可以使用`v-scroll`指令来监听滚动事件。而在Nuxt3中,你可以在组件的生命周期钩子函数`mounted`中使用`$refs`来获取DOM元素。因此,你可以在组件中使用以下代码来实现滚动条触发CSS动画: ```html <template> <div class="container" v-scroll="onScroll"> <div class="content" ref="content"> <!-- Content Here --> </div> </div> </template> <script> export default { methods: { onScroll() { const content = this.$refs.content; const contentTop = content.getBoundingClientRect().top; const windowHeight = window.innerHeight; if (contentTop < windowHeight) { content.classList.add('animate'); } else { content.classList.remove('animate'); } } } } </script> <style> .content { transition: transform 0.5s ease-in-out; } .animate { transform: translateY(50px); } </style> ``` 在这个例子中,我们使用了`v-scroll`指令来监听滚动事件。当滚动事件触发,`onScroll`方法会被调用。在该方法中,我们使用`$refs`来获取`.content`的DOM元素,并使用`getBoundingClientRect()`方法获取该元素的位置信息。然后,我们将窗口的高度与`.content`元素的位置信息进行比较。如果`.content`元素的顶部位置小于窗口高度,则添加`animate`类名,否则移除`animate`类名。在CSS中,我们使用`transition`属性来定义过渡效果,使用`transform`属性来定义动画效果。 请注意,该方法只是一个简单的示例,你可以根据自己的需求调整代码。也可以使用第三方库如`vue-scrollama`来实现更复杂的滚动动画效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值