使用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. 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. Submit form normally to script but append the anchor to the form action URL.

Using AJAX would be the best option. But appending an anchor is the easiest to implement.

Fiddle for the anchor: https://fiddle.jshell.net/vaxdu4n7/9/show/