【问题标题】:Change CSS on page resize在页面调整大小时更改 CSS
【发布时间】:2012-07-19 11:36:47
【问题描述】:

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

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

CSS 文件中只有这个(只有不同​​的背景颜色,所以我可以看到它是否改变了 CSS 表)...

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

问题是当我运行页面时,单词上没有样式,然后当我调整页面大小时它就变黑了,有什么想法吗?

谢谢

【问题讨论】:

  • 您需要在页面加载时调用调整大小,否则在您实际调整大小之前不会调用该函数。

标签: javascript css mobile resize


【解决方案1】:

您可以通过 mediaqueries 仅使用 CSS 来做到这一点。

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

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

  #styleMe {
    background-color: magenta;
  }

}

【讨论】:

  • 需要小心,因为这是 CSS3,一些旧浏览器不支持。
【解决方案2】:

我认为你应该学习如何做响应式网页设计,css3媒体查询很有用

【讨论】:

  • 响应式网页设计并不总是可以仅使用 css,即使使用 css3。我当前项目中的一些更复杂的样式,我必须使用 javascript。我同意研究媒体查询之类的内容,但是您需要注意对旧浏览器的支持。
猜你喜欢
  • 2014-03-14
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多