繁体   English   中英

更改元素的CSS样式

[英]Changing css style of element

我想更改.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>

您的代码在甚至呈现随后的<div class='check-media'></div>之前执行(它位于DOM中的下面)。 您需要等待,直到DOM准备就绪(已加载),然后您才能对其进行更改。

为此,您可以使用以下代码段(需要jQuery):

$(document).ready(function() {
   // your code here
});

您需要在$( 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> 

您可以通过Media Queries单独使用CSS来实现:

@media (max-width: 768px) {
  .check-media {
    background-color: blue !important;
  }
}

.check-media {
    background-color: red;
}

小提琴示例 -更改窗口大小以查看实际效果。

依靠Javascript修改UI被认为是不好的做法。

在其中编写脚本。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM