我想改变.check-media的样式,但这是行不通的。怎么修呢?
<!DOCTYPE html>
<html>
<head>
<style>
.check-media{
width:500px;
background-color:gray;
}
</style>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
if($('.check-media').width() <= 768) {
console.log('You are in width: 768px');
}else{
console.log('You are out of width: 768px');
}
if($(window).width() < 768) {
console.log('screen.width is LESS then 768px');
$('.check-media').css({"background-color":"blue"});
} else {
console.log('screen.width is MORE then 768px');
$('.check-media').css({"background-color":"red"});
}
</script>
</head>
<body>
<h1>My First Heading</h1>
<div class='check-media'>check-media contentn</div>
<p>My first paragraph.</p>
</body>
</html>发布于 2016-01-14 09:57:49
您可以通过媒体查询单独使用CSS实现这一目标:
@media (max-width: 768px) {
.check-media {
background-color: blue !important;
}
}
.check-media {
background-color: red;
}Example fiddle -更改窗口大小以查看它的运行情况。
依赖Javascript来修改UI被认为是错误的做法。
发布于 2016-01-14 09:48:54
您的代码在后续的<div class='check-media'></div>甚至呈现之前就已经执行了(它在DOM中位于下面)。您需要等待,直到DOM准备就绪(加载),然后才能更改它。
为此,您可以使用以下代码段(需要jQuery):
$(document).ready(function() {
// your code here
});发布于 2016-01-14 09:50:42
您需要在$( window ).resize(function()中添加脚本
或
在底部添加脚本,意思是在正文之后添加脚本。
$( window ).resize(function() {
if($('.check-media').width() <= 768) {
console.log('You are in width: 768px');
}else{
console.log('You are out of width: 768px');
}
if($(window).width() < 768) {
console.log('screen.width is LESS then 768px');
$('.check-media').css({"background-color":"blue"});
} else {
console.log('screen.width is MORE then 768px');
$('.check-media').css({"background-color":"red"});
}
}); .check-media{
width:500px;
background-color:gray;
}<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<h1>My First Heading</h1>
<div class='check-media'>check-media contentn</div>
<p>My first paragraph.</p>
https://stackoverflow.com/questions/34786216
复制相似问题