网站在 swift webview HTML CSS 中重新加载时滚动到顶部

Website scrolls to top on reload in swift webview HTML CSS

我正在开发一个网站,但它在重新加载时会滚动到顶部。有什么方法可以防止这种情况发生,因为它使用户更难使用。提前感谢您的帮助!

代码:

<head>
    <title class="noselect">My Website!</title>
</head>
<header>
</header>

<body id='main' class="noselect">
<table class="noselect">
    <p>Test {{ test }}</p>
    <p>Test {{ test1 }}</p>
    <thead>
        <tr>
          <th scope="col">Store</th>
          <th scope="col">Price</th>
          <th scope="col">Add</th>
          <th scope="col">Remove</th>
        </tr>
      </thead>
    <tbody>
        <tr>
            <th><form action="{{ path }}" method="post"><button id='addButton'></button><input type="hidden" name="sender" value="add"></input><input type="hidden" name="name" value="{{ item }}"></input></form></th>
            <th scope="row">{{ quantity[item] }}</th>
            <th id="highlighted">{{ item }}</th>
            <th><form action="{{ path }}" method="post"><button id='removeButton'></button><input type="hidden" name="sender" value="remove"></input><input type="hidden" name="name" value="{{ item }}"></input></form></th>

        </tr>
        <tr>
            <th><form action="{{ path }}" method="post"><button id='addButton' disabled></button><input type="hidden" name="sender" value="add"></input><input type="hidden" name="name" value="{{ item }}"></input></form></th>
            <th scope="row">{{ quantity[item] }}</th>
            <th id="unhighlighted">{{ item }}</th>
            <th><form action="{{ path }}" method="post"><button id='removeButton'></button><input type="hidden" name="sender" value="remove"></input><input type="hidden" name="name" value="{{ item }}"></input></form></th>
        </tr>
</table>
</body>

您可以选择以下方式来防止这种情况发生。

//one way is this

$(window).on('beforeunload', function() {
    $(window).scrollTop(0);
});


//Reset scroll top 

    history.scrollRestoration = "manual"

    $(window).on('beforeunload', function(){
          $(window).scrollTop(0);
    });
    
    
//JS 

window.onunload = function(){ window.scrollTo(0,0); }


// Other way

$(document).ready(function() {
var url = window.location.href;
console.log(url);
if( url.indexOf('#') < 0 ) {
    window.location.replace(url + "#");
} else {
    window.location.replace(url);
}

//another one

    var objDiv = document.getElementById("your id");
if ( window.history.replaceState ) {
  objDiv.scrollTop = objDiv.scrollHeight;

    window.history.replaceState( null, null, window.location.href );
}

var objDiv = document.getElementById("your id");
if ( window.history.replaceState ) {
  objDiv.scrollTop = objDiv.scrollHeight;
  window.history.replaceState( null, null, window.location.href );
}