JS平滑滚动代码报错Uncaught ReferenceError: target未定义,求解决方案
修复Uncaught ReferenceError: target is not defined的平滑滚动JavaScript代码
嘿,这个错误其实很好解决——你遇到的Uncaught ReferenceError: target is not defined,本质是代码里用到了target变量,但它从来没被声明或赋值就直接使用了。咱们来一步步把它修好:
错误根源
你的SmoothScroll函数第一个参数是body,但函数内部直接跳去判断if (target === document),这时候target还完全没定义,浏览器自然会报错。你需要先把传入的body参数赋值给target,再进行后续的兼容性处理。
修复后的完整代码
function init(){ new SmoothScroll(document,30,24) } function SmoothScroll(body, speed, smooth) { // 先把参数赋值给target,补上变量声明 let target = body; // 再进行跨浏览器的document滚动对象兼容处理 if (target === document) { target = (document.scrollingElement || document.documentElement || document.body.parentNode || document.body) } var moving = false var pos = target.scrollTop var frame = target === document.body && document.documentElement ? document.documentElement : target // safari兼容性处理 target.addEventListener('mousewheel', scrolled, { passive: false }) target.addEventListener('DOMMouseScroll', scrolled, { passive: false }) function scrolled(e) { e.preventDefault(); // 禁用默认滚动行为 var delta = normalizeWheelDelta(e) pos += -delta * speed pos = Math.max(0, Math.min(pos, target.scrollHeight - frame.clientHeight)) // 限制滚动范围 if (!moving) update() } function normalizeWheelDelta(e){ if(e.detail){ if(e.wheelDelta) return e.wheelDelta/e.detail/40 * (e.detail>0 ? 1 : -1) // Opera兼容性 else return -e.detail/3 // Firefox兼容性 }else return e.wheelDelta/120 // IE,Safari,Chrome兼容性 } function update() { moving = true var delta = (pos - target.scrollTop) / smooth target.scrollTop += delta if (Math.abs(delta) > 0.5) requestFrame(update) else moving = false } var requestFrame = function() { // requestAnimationFrame跨浏览器兼容 return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(func) { window.setTimeout(func, 1000 / 50); } ); }() }
关键修改说明
- 新增了
let target = body;:把函数传入的body参数赋值给target,同时用let声明变量,确保它在函数作用域内有定义 - 调整了兼容性判断的顺序:先声明并赋值
target,再判断是否为document并替换为合适的滚动元素
这样修改后,浏览器就不会再抛出target未定义的错误,你的平滑滚动功能应该就能正常工作了。
内容的提问来源于stack exchange,提问作者Marcus
相关产品推荐
相关产品推荐

