场景:页面A使用第三方插件C,如果页面刷新,C会重新初始化并且无法记录之前的信息。现在希望页面的主要功能区B刷新,但是C的信息不要丢失。
解决方案:B采用iframe方式引入到A中,B刷新采用self.location.reload(),这时B内容刷新,而A中除了B以外的其他内容保持不变。A需要刷新可以使用top.location.reload()。
局部刷新一般就是采用ajax或者iframe(frameset)的方式,这里之所以用iframe,是因为B中内容很多,用ajax控制起来比较麻烦。
如果还有其他的好方法,请大家留言帮助,将非常感谢!
demo:
A页面:
<!--主界面index.html--> <iframe src="frame.html" frameborder="1" style="width:500px;height:300px;"></iframe> <h1 id="iframeout">框架外内容</h1> <button onclick="fresh()">框架外刷新</button> <script> var h1 = document.getElementById('iframeout'); function iframeout(){ h1.style.color = "yellow"; h1.innerText = "我变化了"; } setInterval(iframeout, 5000); function fresh(){ // 框架主页面刷新,可以实现下面两个功能: top.location.reload(); //刷新整页 // window.parent.location.href='http://koushuling.top'; //框架页重定向 } </script>
B页面:
<h1 id="test">框架内页面</h1> <button onclick="fresh()">框架内刷新</button> <script> var h1 = document.getElementById('test'); function test(){ h1.style.color = "red"; h1.innerText = "我变化了"; } setInterval(test, 2000); function fresh(){ // 框架内页面刷新:可实现局部刷新与整个页面重定向 self.location.reload(); //刷新框架内页面 // window.parent.location.href='http://koushuling.top'; //页面重定向 } </script>
关于iframe的高度自适应的文章,文章很早了,但是思路还是由很多用处的:http://www.zhangxinxu.com/wordpress/?p=1294