There was a requirement yesterday, hoping that the page will automatically scroll to the left after loading.
I always thought that just set a value to the page's document.documentElement.scrollLeft and it took effect, but I was disappointed~
I took the time to check today and found out:
Use document.documentElement.scrollLeft to set the value, which must be effective only if triggered by a human event;
If you want the page to automatically scroll a certain distance when it is loaded, use jquery's animate, as shown in the following example:
$("html,body").animate({"scrollLeft": "300px"}, 1000);
$("html,body").animate({"scrollTop": "300px"}, 1000);
demo:
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Auto scroll</title>
<meta name="keywords" content=""/>
<meta name="description" content=""/>
<script type="text/javascript" src="https://www.gamebox.com/js/jquery.js"></script>
</head>
<body>
<!-- container start -->
<div style="height: 3000px; width: 3000px;">
<a href="javascript:;">Click</a>
</div>
<!-- container end -->
<script type="text/javascript">
/*window.onload = function(){
window.scroll(0,300);
$(".btn").on("click", function(){
document.documentElement.scrollLeft = "500";
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
var oLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
alert(oLeft);
});
}*/
$(function(){
$("html,body").animate({"scrollLeft": "300px"}, 1000);
});
</script>
</body>
</html>