简体   繁体   中英

How to change background color in javascript

Is there any what I could change the background color with javascript? For example:

<div id="factboxes">
        <div id="counter">
           <div class="factbox">
                <div class="counter-value "><?php echo end($total); ?></div>
                <p>Total Number Of Human Count</p>
          </div>
          
           <div class="factbox factboxgap">
                <div class="counter-value "><?php echo end($current); ?></div>
                <p>Current Number Of Human Count</p>
           </div>
           
           <div class="factbox factboxgap">
                <div class="counter-value "><?php echo count($reserve); ?> </div>
                <p>Total Number of Reservation</p>
           </div>
        </div>
    </div>

    <script>
        if (<?php $total?> < 85){
            document.div.factbox.backgroundColor = "green";
        }
    </script>

If the total is less than 85 then the background color will be green. I tried to code in this way but nothing happen. I'm still new with javascript, hope someone could help me and explain how should it be done. Thank you

Try this

<div id="factboxes">
    <div id="counter">
       <div class="factbox" id="TotalDiv">
            <div class="counter-value "><?php echo end($total); ?></div>
            <p>Total Number Of Human Count</p>
      </div>
      
       <div class="factbox factboxgap">
            <div class="counter-value "><?php echo end($current); ?></div>
            <p>Current Number Of Human Count</p>
       </div>
       
       <div class="factbox factboxgap">
            <div class="counter-value "><?php echo count($reserve); ?> </div>
            <p>Total Number of Reservation</p>
       </div>
    </div>
</div>

<script>
    if (<?php echo $total; ?> < 85){
        document.getElementById("TotalDiv").style.backgroundColor = "green";
    }
</script>

EDIT: fixed typo in javascript

You can use document.body.style.backgroundColor to change the color.

Read more about it on W3SChools: https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp

since you have already assigned class name as factbox , you can simply use this code:

document.getElementsByClassName("factbox")[0].style.backgroundColor = "green"

The [0] is to select the 1st element from the returned array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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