如何阻止点击iframe关联链接后页面自动滚动到顶部?
解决iframe显示时页面自动滚动到顶部的问题
问题原因
你的a标签使用了href="#xxx"格式的锚点链接,但目标iframe初始状态是display: none,浏览器无法定位到隐藏元素,会默认滚动到页面顶部。
两种解决方法
方法1:修改a标签的href属性
把所有a标签的href="#xxx"替换为href="javascript:void(0)",彻底取消锚点跳转行为:
<dt><a class="kinetic" href="javascript:void(0)" onclick="clickMe()">Izanagi's Burden.</a></dt> <dt><a class="arc" href="javascript:void(0)" onclick="clickMe2()">Forbearance.</a></dt> <dt><a class="solar" href="javascript:void(0)" onclick="clickme3()">The Lament.</a></dt>
方法2:在点击事件中阻止默认行为
在onclick事件末尾添加return false;,阻止a标签的默认跳转动作:
<dt><a class="kinetic" href="#izanagisBurden" onclick="clickMe(); return false;">Izanagi's Burden.</a></dt> <dt><a class="arc" href="#forbearance" onclick="clickMe2(); return false;">Forbearance.</a></dt> <dt><a class="solar" href="#theLament" onclick="clickme3(); return false;">The Lament.</a></dt>
或者在JavaScript函数内部添加阻止默认行为的代码(需传入event参数):
function clickMe(event) { event.preventDefault(); // 阻止默认跳转 // 原函数逻辑保持不变 document.getElementById('izanagisBurden').src="https://www.light.gg/db/items/3211806999/izanagis-burden/"; document.getElementById('izanagisBurden').style.display=''; document.getElementById('forbearance').style.display='none'; document.getElementById('theLament').style.display='none'; }
对应的a标签要传入event参数:
<dt><a class="kinetic" href="#izanagisBurden" onclick="clickMe(event)">Izanagi's Burden.</a></dt>
说明
推荐方法1或方法2的return false写法,操作简单易理解,修改后点击链接只会触发iframe的显示/隐藏切换,不会再出现页面滚动到顶部的问题。
内容的提问来源于stack exchange,提问作者Zlayxa
相关产品推荐
相关产品推荐

