简体   繁体   中英

$(document.body).css not working

I have been trying to change the background image of my HTML body with a .js but nothing happens. Do I need to put the Javascript code inside my HTML?

function plano1() {
    alert('you');
    $(document.body).css('background-image', 'url(img/planoSelected.png)');
}

This is the complete function I have been trying to do. Google Chrome shows the alert, but doesn't do the $(document.body) . What am I supposed to do?

Notes : I use the function with a "onmouseover". I have already tried to use:

$('body').css('background-image', 'url(img/planoSelected_2.png)');

$("body").css('background-image', 'url(img/planoSelected_2.png)');

The jQuery code should be called at the bottom of the page, above the closing body tag.

Load jQuery first:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function() {
        $('body').css('background-image', 'url(img/planoSelected_2.png)');
    });

</script>

The code is fine, but there are a few reasons why this might not work.

  1. Make sure the image paths are correct, relative to the script's location
  2. Is plano1 called?
  3. Make sure jQuery is actually loaded
  4. Make sure the DOM is ready when calling the function (use $(document).ready if not sure)
  5. Make sure there are no errors in the code before plano1 is called

If these things are all right, and it still doesn't work, check if your onmouseover is working at all. Simply alert or log something in the console.

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