为何scrollIntoView()无法滚动到指定的update-form元素?
问题修复方案
问题出在<a>标签的默认行为上:你用了href="#",点击后浏览器会先执行onclick里的selectPost函数,随后触发默认的锚点跳转动作——滚动到页面顶部,这就覆盖了你调用scrollIntoView的效果。
给你三种可行的修复方式:
方式一:在onclick里返回false阻止默认行为
修改生成Update链接的代码:
<a href="#" class="card-link" onclick="selectPost('${post.id}', '${post.title}', '${post.body}'); return false;">Update</a>
return false会阻止<a>标签的默认跳转动作,让scrollIntoView的滚动效果正常生效。
方式二:修改href为javascript:void(0)
把链接的href值改成javascript:void(0),从根源上取消默认跳转:
<a href="javascript:void(0)" class="card-link" onclick="selectPost('${post.id}', '${post.title}', '${post.body}')">Update</a>
javascript:void(0)会让链接点击后不执行任何默认跳转行为。
方式三:通过事件对象阻止默认行为
先修改链接的onclick,传递事件参数:
<a href="#" class="card-link" onclick="selectPost(event, '${post.id}', '${post.title}', '${post.body}')">Update</a>
然后修改selectPost函数,添加事件参数并阻止默认行为:
function selectPost(event, id, title, body) { event.preventDefault(); // 阻止a标签的默认跳转 window.idToUpdate = id; document.getElementById('title-edit').value = title; document.getElementById('body-edit').value = body; document.getElementById('update-form').scrollIntoView({behavior: "smooth"}); }
以上三种方式任选其一,都能解决页面滚动到顶部的问题,让页面正常滚动到update-form表单位置。
内容的提问来源于stack exchange,提问作者Vladikslavus
相关产品推荐
相关产品推荐

