简体   繁体   English

用 javascript 修改 CSS

[英]Modify a CSS with javascript

Hi i'm having trouble changing the class of a CSS with javascript, whenever I call the element and try to change the style it returns null, almost like the element doesn't have the class associated my code looks like this Hi i'm having trouble changing the class of a CSS with javascript, whenever I call the element and try to change the style it returns null, almost like the element doesn't have the class associated my code looks like this

 var box = document.getElementById('box1'); box.style.backgroundColor = red;
 .box { background-color: black; }
 <div id=“box1“ class="box">

Somehow when you log in the console the style of box (of the js) the background color is empty不知何故,当您登录控制台时(js的)框样式背景颜色为空

Use correct quotations around your ID attribute.在您的 ID 属性周围使用正确的引号。 Also use "red" instead of just red.也使用“红色”而不仅仅是红色。

 var box = document.getElementById('box1'); box.style.backgroundColor = "red";
 .box { background-color: black; }
 <div id="box1" class="box"> CSS </div>

this should work这应该工作

  var box = document.getElementById('box1');
  box.style.backgroundColor = "red"; //you were just typing red earlier
  box.style.width="100px";
  box.style.height="100px";

 setTimeout(function() { $(".box").css("background-color", "red"); }, 3000);
 .box { background-color: black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div id=“box1” class="box">Box 1</div>

You can change CSS using.css() of jquery.您可以使用 jquery 的.css() 更改 CSS。

Try:尝试:

 $( document ).ready(function() { $('#box1').css("background-color", "red") })
 .box { background-color: black; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <div id="box1" class="box"> CSS </div>

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

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