[解决] VUE项目中使用@scroll获取不到事件对象,结果undefined
考虑为什么获取不到事件对象
原因1:获取或书写的方式有问题
原因2:样式的 overflow: scroll
原因3:没有给父盒子设置固定高度
原因4:浏览器兼容问题
…
几种解决办法
- 兼容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 } } }
- 设置css
.overview { // 给父元素设置固定高度 height: 600px; // 设置可滚动 overflow-y: auto; }
- 绑定事件,禁止冒泡
window.addEventListener('scroll', (e) => { console.log(e) }, true)
如果只想在页面内进行跳转可使用
Element.scrollIntoView()
方法让当前的元素滚动到浏览器窗口的可视区域内。
TYPE | params | default |
---|---|---|
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”});