点击iframe内元素时如何让父页面滚动到指定锚点
解决方案
错误原因
window.parent.scrollTo() 原生仅支持两种传参格式,不支持直接传入选择器字符串、jQuery对象作为参数,所以你之前的写法无法生效:
- 双数值参数:
scrollTo(水平偏移量, 垂直偏移量) - 选项对象参数:
scrollTo({top: 垂直偏移量, left: 水平偏移量, behavior: 'smooth'/*可选平滑滚动*/})
正确实现(仅支持同域iframe场景,跨域下受浏览器安全限制无法操作父页面DOM)
纯原生JS写法
// 获取父页面目标元素 const target = window.parent.document.getElementById('xyz') if (target) { // 计算元素相对于整个父页面顶部的距离 const targetTop = target.getBoundingClientRect().top + window.parent.pageYOffset window.parent.scrollTo({ top: targetTop, left: 0, behavior: 'smooth' // 不需要平滑滚动可删除该行 }) }
jQuery写法(需父页面已引入jQuery)
const $target = window.parent.$('#xyz') if ($target.length) { window.parent.scrollTo(0, $target.offset().top) }
内容的提问来源于stack exchange,提问作者user17431675
相关产品推荐
相关产品推荐

