简体   繁体   English

使用JavaScript提交表单后,如何返回到原始滚动位置?

[英]How to return to original scroll position after submitting a form using javascript?

How can I automatically scroll back to the position of the button after submitting my form? 提交表格后如何自动退回到按钮的位置?

function scrollToButtonPosition(x,y){
  window.scrollTo(x,y);
}

How do i call this function and pass the current scroll coordinates when i click the submit button? 单击提交按钮时,如何调用此函数并传递当前滚动坐标?

You have a few options to achieve that. 您可以选择几种方法来实现。

  • Use AJAX to submit the form to the script. 使用AJAX将表单提交到脚本。 Scroll position will be maintained 滚动位置将保持不变
  • On submit save the scroll position into local storage and on load look if this item is in local storage, if so scroll to it and delete item in local storage. 在提交时,将滚动位置保存到本地存储中,并在加载时查看此项目是否在本地存储中,如果滚动,请滚动到该位置并删除本地存储中的项目。 If not, this page didn't get loaded due to form submission. 如果不是,则由于提交表单而无法加载此页面。
  • Using a anchor. 使用a锚。 Submit form normally to script but append the anchor to the form action URL. 通常将表单提交到脚本,但将锚添加到表单操作URL。

Using AJAX would be the best option. 使用AJAX将是最好的选择。 But appending an anchor is the easiest to implement. 但是添加锚点是最容易实现的。

Fiddle for the anchor: https://fiddle.jshell.net/vaxdu4n7/9/show/ 锚的小提琴: https : //fiddle.jshell.net/vaxdu4n7/9/show/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM