简体   繁体   English

如何使用javascript更改div的背景颜色

[英]How to change background color of div with javascript

I know this may seem very simple to many, but for me it isn't, so im here asking for your help.我知道这对很多人来说似乎很简单,但对我来说却不是,所以我在这里寻求您的帮助。

I have a javascript function that returns some colors, and then a have a seperate div which should accept background color that comes from that function.我有一个返回一些颜色的 javascript 函数,然后有一个单独的 div,它应该接受来自该函数的背景颜色。

i get the result of function like this:我得到这样的函数结果:

var _myColor = GenerateColor(value).color;

and the result of _myColor is: #742322 _myColor 的结果是: #742322

How would i force this color now inside div as my background-color我现在如何在 div 中强制使用这种颜色作为我的背景颜色

<div class="myColorClass" stlye="background-color:"></div>

Thank you!谢谢!

JQuery provides a method called .css() . JQuery 提供了一个名为.css()的方法。 If you pass one attribute (the css property like background-color ) you get the value of this property.If you pass a second one, the second one will be the property's value.如果您传递一个属性(例如background-color的 css 属性),您将获得此属性的值。如果您传递第二个属性,则第二个将是该属性的值。

 $("#mydiv").css("background-color", "#F0F0F0");
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mydiv">This is my div.</div>

尝试这个:

 document.getElementsByClassName('myColorClass')[0].style.backgroundColor = color;

here is another solution with pure java script enjoy coding这是另一个使用纯 Java 脚本享受编码的解决方案

  <div>
   <form>
      <input type="text" placeholder="first input"></input>
      <input id="secondtext" type="text" placeholder="second text"></input>
   </form>
</div>
<div id="div1">
   hello
</div>
<button onclick="backcolor()">ClickToChangeColor</button>
function backcolor()
{
   document.getElementById('div1').style.backgroundColor = 'red';
} 

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

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