更改页面上的CSS调整大小

Car*_*yds 1 javascript css mobile resize

我把这段代码放在一起......

<title>Style Change on Resize</title>
<script type="text/javascript">

function resize() {

if (screen.width <= 640)

{document.write("<link href='style1.css' rel='stylesheet' type='text/css'>")}

else

{document.write("<link href='style2.css' rel='stylesheet' type='text/css'>")}
}

</script>
</head>

<body onResize="resize();">

<div id="styleMe">This is a test of a resize javascirpt that will change its CSS sheet    
when the browser window is resized, or when being viewed on a mobile device, such as     
iOS, etc. Hello.</div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)

并且CSS文件中只有它们(只有不同​​的背景颜色,所以我可以看到它是否更改了CSS表格)...

#styleMe {
background-color:#309;
height:200px;
width:100%;
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我运行页面时,单词上没有样式,那么当我调整页面大小时,它只会变黑,任何想法?

谢谢

Max*_*ens 7

您可以使用仅使用CSS的媒体查询来执行此操作.

#styleMe {
  background-color:#309;
  height:200px;
  width:100%;
}

@media only screen and (max-width: 640px) {

  #styleMe {
    background-color: magenta;
  }

}
Run Code Online (Sandbox Code Playgroud)