简体   繁体   中英

Changing css background with javascript

I want to use js to change the background color that is set to white in the css. Not sure why nothing is happening.

.html
document.getElementById("invoice-box").style.background = "red";
.css
 .invoice-box { background: white; max-width:800px; margin:auto; padding:30px; border:1px solid #eee; box-shadow:0 0 10px rgba(0, 0, 0, .15); font-size:16px; line-height:24px; font-family:'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; color:#555; 
.js
 document.getElementById("invoice-box").style.background = "red"; 
document.querySelector(".invoice-box").style.background = "red";

使用querySelector怎么样?

You have used getElementById which fetches html elements from Id, but you have defined invoice-box as class. Define it to id as well

<body>
<div class="invoice-box" id="invoice-box">
    <table cellpadding="0" cellspacing="0">
        <tr class="top">
            <td colspan="2">
                <table>
                    <tr>
                        <td class="title">
                            <img src="emoji.png" width="100">
                        </td>

If you can use jquery just do as sample

$('#element').css('background-color', '#ffffff') 

Note: #ffffff = white color

您正在使用类并在javascript中调用ID,请使用代替类

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