VUE项目中使用@scroll获取不到事件对象,结果undefined

[解决] VUE项目中使用@scroll获取不到事件对象,结果undefined

考虑为什么获取不到事件对象

原因1:获取或书写的方式有问题
原因2:样式的 overflow: scroll
原因3:没有给父盒子设置固定高度
原因4:浏览器兼容问题

几种解决办法

  1. 兼容scrolltop
    export default {
      methods: {
        changeScroll(e) {
          // 文档的总高度
          const documentScrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
          // 浏览器窗口的高度
          const getWindowHeight = document.documentElement.clientHeight || document.body.clientHeight
          // 滚动条在y轴上的滚动距离
          const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        }
      }
    }
    
  2. 设置css
    .overview {
        // 给父元素设置固定高度
        height: 600px;
        // 设置可滚动
        overflow-y: auto;
      }
    
  3. 绑定事件,禁止冒泡
    	window.addEventListener('scroll', (e) => {
          console.log(e)
        }, true)
    

如果只想在页面内进行跳转可使用

Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。

TYPEparamsdefault
behavior (动画过渡效果)"auto"或 “smooth”"auto"
block (垂直方向的对齐)“start”, “center”, “end”, 或 “nearest”"start"
inline (水平方向的对齐)“start”, “center”, “end”, 或 “nearest”"nearest"

var element = document.getElementById(“box”);

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({block: “end”});
element.scrollIntoView({behavior: “smooth”, block: “end”, inline: “nearest”});

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值