首页 > web前端 > js教程 > 正文

JS实现响应式的简单代码

PHPz
发布: 2017-04-03 15:33:38
原创
2208 人浏览过

一、CSS实现响应式

CSS响应式的实现主要依赖于CSS媒体查询:

媒体查询包含一个可选的媒体类型和零或多个表达式来限制使用媒体特性的样式表范围,例如:width,height,color。CSS3中的Media queries让内容的呈现可以只针对特定范围的输出设备而不必去改变内容本身。即通过媒体查询判断屏幕宽度,加载不同的CSS样式表

代码如下:注意一定要有一个默认样式表不加媒体查询,否则在IE8中访问时会没有样式表。

<head>

  <meta charset="UTF-8">

  <title>响应式的演示</title>

  <link rel="stylesheet" type="text/css" href="css/reset.css" />

  <link rel="stylesheet" type="text/css" href="css/index1200.css" />

  <link rel="stylesheet" type="text/css" href="css/index980.css" media="screen and (min-width:980px) and (max-width:1200px)"/>

  <link rel="stylesheet" type="text/css" href="css/index640.css" media="screen and (min-width:640px) and (max-width:980px)"/>

  <link rel="stylesheet" type="text/css" href="css/index320.css" media="screen and (max-width:640px)"/>

</head
登录后复制

二、JS实现响应式

JS响应式的实现也是依托于外联不同的CSS样式表,通过获取不同设备的屏幕宽度,选择性加载不同的CSS样式表。

<head>  <meta charset="UTF-8">  <title>响应式的演示</title>  <link rel="stylesheet" type="text/css" href="css/reset.css" />  <link rel="stylesheet" type="text/css" href="css/index1200.css" />  <link rel="stylesheet" href="" id="rwdlink" />  <script type="text/javascript">    var rwdlink = document.getElementById("rwdlink");

    setCSS();

    window.onresize = setCSS;

    function setCSS(){

      var windowWidth = document.documentElement.clientWidth;

      if(windowWidth >= 1200){

        rwdlink.href = "";

      }else if(windowWidth >= 980){

        rwdlink.href = "css/index980.css";

      }else if(windowWidth >= 640){

        rwdlink.href = "css/index640.css";

      }else{

        rwdlink.href = "css/index320.css";

      }

    }

  </script></head>
登录后复制

 

以上是JS实现响应式的简单代码的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!