【前端/JS】刷新网页后先前浏览位置不变的处理方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wzl505/article/details/82979783

刷新网页后先前浏览位置不变的处理方法

<script>
	function window.onbeforeunload(){
		var scrollPos;    
		if (typeof window.pageYOffset != 'undefined') {
		   scrollPos = window.pageYOffset;
		}
		else if (typeof document.compatMode != 'undefined' &&
			 document.compatMode != 'BackCompat') {
		   scrollPos = document.documentElement.scrollTop;
		}
		else if (typeof document.body != 'undefined') {
		   scrollPos = document.body.scrollTop;
		}
		document.cookie="scrollTop="+scrollPos; //存储滚动条位置到cookies中
    }
	function window.onload()
	{ 
		if(document.cookie.match(/scrollTop=([^;]+)(;|$)/)!=null){
			var arr=document.cookie.match(/scrollTop=([^;]+)(;|$)/); //cookies中不为空,则读取滚动条位置
			document.documentElement.scrollTop=parseInt(arr[1]);
			document.body.scrollTop=parseInt(arr[1]);
		}
	}
</script>

方法二:

使用iframe框架:

<iframe id="frame3d" name="frame3d" frameborder="0" width="100%" scrolling="auto"
 style="margin-top: -4px;" onload="this.style.height=document.body.clientHeight-84"
 height="100%" src="http://www.5202m.com" mce_src="http://www.baidu.com">

</iframe>

缺点是,存在跨域访问的问题。

推荐后台使用,前台对搜索引擎不友好,不利于优化。

猜你喜欢

转载自blog.csdn.net/wzl505/article/details/82979783