网站判断手机或电脑来显示不同的iframe框架内容 实现显示与隐藏

时间:2021-11-24
类别:教程 - 网页设计

在设计网站时,要通过不同的设备,来显示不同的iframe框架内容,要通过判断手机端与电脑端来显示与隐藏,这里需要编写一个JS来实现。

一、编写一个JS,把他命名为pc_or_mobile.js 上传到源站的根目录中。

比如您打算存放js的站域名为 https://www.uu2018.com/

则可以把js放在https://www.uu2018.com/网站服务器的根目录中,当在其它网站上引入时,就可以这样写了

  1. <script src="https://www.uu2018.com/pc_or_mobile.js"></script> 

pc_or_mobile.js这个文件中的内容为:

  1. if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {  
  2.  
  3. //移动端 
  4.  
  5. document.writeln("<div style='margin:0 auto;width:100%;text-align:center;;-position:relative;overflow:hidden'><iframe src='https://www.sina.com/'margin-top: 0px; position: relative;left:0; width='100%'height='1800' frameborder='0' ></iframe></div>"); 
  6.  
  7. }else
  8.  
  9.     document.writeln("<div style='margin:0 auto;text-align:center;position:relative;overflow:hidden'><iframe scrolling='no' src='https://www.baidu.com/' width='1200'height='3700' frameborder='0' align='middle' style='margin-top: -90px; position: relative;left:0;'></iframe></div>"); 
  10.  
  11.     //上面margin-top: -90px;的作用是隐藏对方网站的logo,导航条等,不需要时,可以设置为0 
  12.  

二、假如js放在https://www.uu2018.com/网站根目录中

a站要显示这个js中的内容,则增加js调用,(电脑上,需要ctrl+f5 刷新,才可正常显示修改效果)。

模板上直接添加以下代码:

  1. <script type="text/javascript" src="https://www.uu2018.com/pc_or_mobile.js"></script> 

如果不希望手机上有缓存,方便刷新调试查看.可以这样调用:

  1. <script> 
  2.     document.write('<script src="https://www.uu2018.com/pc_or_mobile.js?adv='+Math.random()+'"></script>'); 
  3. </script> 
    收藏