简体   繁体   中英

Loading a background-color for a div when page is loaded

I wrote a simple code where I'm trying to load a background-color to a div when page loads. Here is the code:

<div id="offerOne">
    <img src="images/images.jpg" class="img-responsive center-block" alt="img">
</div>  

Javascript:

<script type="text/javascript">
    $('#offerOne').attr('style', 'background-color: #f12 !important');
</script>  

But this isn't loading background-color for div when page loads. How can I do it?

You should put your code inside Dom ready,

$(function(){
  $('#offerOne').attr('style', 'background-color: #f12 !important');
})

 $('#offerOne').css('background-color', '#f12'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="offerOne"> <img src="images/images.jpg" class="img-responsive center-block" alt="img"> </div> 

try

use

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

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