JS和CSS实现响应式

一、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>

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值