Laravel 10中scrollIntoView与scrollTo函数无法生效问题排查
Laravel 10中点击按钮滚动到下一个元素失败的问题排查与修复
核心问题及修复方案:
事件绑定时机错误
你代码里window.onload = Controls.init();是直接执行init方法,把返回值(undefined)赋值给了window.onload,而非绑定函数引用。这会导致init在DOM元素还没渲染完成时就执行,nextbuttons、prevbuttons这些集合是空的,事件根本没绑定到按钮上,点击自然没反应。
修正写法:// 要么用函数引用 window.onload = Controls.init; // 更推荐用DOMContentLoaded,DOM构建完成就触发,无需等待资源加载 document.addEventListener('DOMContentLoaded', Controls.init);nextslide方法逻辑偏差
你已经获取到了下一个question元素,但没利用它,反而用window.scrollTo(0, window.innerHeight)固定滚动到视口高度位置,这和目标元素的实际位置无关。改成直接滚动到目标元素:nextslide: function (e) { let id = e.target.closest(".question").firstElementChild.id; var question = document.getElementById(parseInt(id) + 1); // 先判断元素是否存在,避免报错 if (question) { question.scrollIntoView({ behavior: "smooth", block: "center"}); } },未处理元素不存在的边界情况
当处于第一个/最后一个question时,获取的上一个/下一个元素会不存在,直接调用scrollIntoView会抛出错误中断代码。必须加判断:prevslide: function (e) { let id = e.target.closest(".question").firstElementChild.id; var prevQuestion = document.getElementById(parseInt(id) - 1); if (prevQuestion) { prevQuestion.scrollIntoView({ behavior: "smooth", block: "center"}); } },polyfill使用问题
你导入了seamless-scroll-polyfill但没使用它提供的scrollIntoView方法,若要兼容旧浏览器,需替换原生调用:scrollIntoView(question, { behavior: "smooth", block: "center"});现代浏览器原生支持平滑滚动,若无需兼容旧浏览器可忽略此步骤。
修复后的完整代码:
import {polyfill, scrollIntoView} from "seamless-scroll-polyfill"; polyfill(); var Controls = { questions: document.getElementsByClassName('question'), center_questions: document.getElementsByClassName('center-question'), nextbuttons: document.getElementsByClassName('next'), prevbuttons: document.getElementsByClassName('prev'), header: document.getElementById('header'), init: function (){ for (let button of this.nextbuttons) { button.addEventListener("click", e => { this.nextslide(e); }); } for (let button of this.prevbuttons) { button.addEventListener("click", e => { this.prevslide(e); }); } }, nextslide: function (e) { let id = e.target.closest(".question").firstElementChild.id; var question = document.getElementById(parseInt(id) + 1); if (question) { scrollIntoView(question, { behavior: "smooth", block: "center"}); } }, prevslide: function (e) { let id = e.target.closest(".question").firstElementChild.id; var prevQuestion = document.getElementById(parseInt(id) - 1); if (prevQuestion) { scrollIntoView(prevQuestion, { behavior: "smooth", block: "center"}); } }, } document.addEventListener('DOMContentLoaded', Controls.init);
内容的提问来源于stack exchange,提问作者Luca Pisoni
相关产品推荐
相关产品推荐

