我想更改.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>
答案 0 :(得分:2)
您的代码在后续<div class='check-media'></div>
呈现之前执行(它位于DOM中的下方)。你需要等待,直到DOM准备好(加载)然后你可以改变它。
为此,您可以使用以下代码段(需要jQuery):
$(document).ready(function() {
// your code here
});
答案 1 :(得分:2)
您需要在$( 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>
答案 2 :(得分:0)
您可以通过媒体查询单独使用CSS实现此目的:
@media (max-width: 768px) {
.check-media {
background-color: blue !important;
}
}
.check-media {
background-color: red;
}
Example fiddle - 更改窗口大小以查看其效果。
依靠Javascript来修改UI被认为是不好的做法。
答案 3 :(得分:0)
在里面写下你的脚本。
$(document).ready(function(){
write script here!
})
或者,请检查以下代码。
<!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>
$(document).ready(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"});
}
});
</script>
</head>
<body>
<h1>My First Heading</h1>
<div class='check-media'>check-media contentn</div>
<p>My first paragraph.</p>
</body>
</html>
&#13;