简体   繁体   中英

How change background image with javascript onClick on a link

I want a background image to change with the onclick attribute on html link tag. But its not working.

<ul>
    <li><a href="index.php?page=Home" onclick="one();">Home</a> </li>
    <li><a href="index.php?page=Achivement" onclick="two();">Achivement</a></li>

    <li><a href="index.php?page=Career" onclick="three();">Career</a></li>
    <li><a href="index.php?page=Message" onclick="four();">Message</a></li>
    <li><a href="index.php?page=opportunity">opportunity</a></li>
    <li><a href="upload1.php">Register</a>
    <li></li>
 </ul>
  <script type="text/javascript">
  function one(){

 $('body').css('background-image','url(image/back1.jpg)');

}
function two(){

   $('body').css('background-image','url(image/back2.jpg)');

}
function three(){


}
function four(){


}  </script>

as you can see I tried passing a function on the onclick attribute and I have already defined these function on the bottom already and still the background image wont change. I have checked the directory where the images are they are correct. and I havent defined any background image on my css so. I need help and its driving me crazy.

A couple things:

  1. You need to include the jQuery library (in case you did not already)
  2. You need to prevent the default action because it is a link
  3. You need to functionalize it for reuse.

Example:

<script type="text/javascript">
    $(function(){
        $('a').on('click',function(e){
            var href = this.href.split('='),
                img;

            // prevents following to the link location
            e.preventDefault();

            // determines which background image
            switch(href[1]){
                case 'Home':
                   img = 'back1.jpg';
                   break; 
                case 'Achievement':
                   img = 'back2.jpg';
                   break;
                case 'Career':
                   img = 'back3.jpg';
                   break;
                case 'Message':
                   img = 'back4.jpg';
                   break;
                case 'Opportunity':
                   img = 'back5.jpg';
                   break;
            }

            // assigns background-image
            $('body').css({backgroundImage:'url(image/'+img+')'});
        });
    });
</script>

This will allow great reuse, and eliminate the need for the inline onclick= declarations.

You have an href along with the click. You will need to specify your link as

<li><a href="#" onclick="one();">Home</a> </li>

You will need to redirect to the page through javascript. Otherwise you are in essence asking it to go to redirect you to the URL and call your javascript but if the redirect happens how would you even see what the javascript execution yields?

Remove your inline script and all your functions and try this instead:

$(function () {
    $('ul li a').on('click', function (e) {
        e.preventDefault)();
        $('body').css('background-image', 'url(image/back' + $(this).closest('li').index() + '.jpg)');
    });
});

If you just want to target the first 4 li you can add to my code a if($(this).closest('li').index() < 5){ change background };

About the links you have, if you want to use them

Try to use this stetment for jQuery element:

$(function() {
  $('elementLink').on('click', function(e){
       e.preventDefault();
       $('body').css('background-image','url(image/back1.jpg)');
  });
});

It should be like this:

onclick="one(); return false;"

when you click a link, the new page loads, so you have to prevent this behavior by writing return false

You can also write

onclick="return one();"

and javascript:

function one(){
  $('body').css('background-image','url(image/back1.jpg)');
  return false;
}

I would always try to keep the image src decision out of the code, and move it into the CSS file. Something like:

// could be good to keep your url params as lower case as a convention, then this
// options object could be skipped and you'd just use the param as the classname
var options = {
  'Home': 'home',
  'Achievement': 'achievement'
};

$("ul li a").click(function(e){
  e.preventDefault();

  var href = $(this).attr("href");

  if(href[1])
  {
    $("body").addClass(options[href[1]]);
  }

});

then in your css file

body.achievement
{
  background: url("/images/some_img.png");
}

body.home
{
  background: url("/images/some_img2.png");
}

That way when you want to update the srcs, or styles, you do't have to go searching through the src

ps I haven't run the code above, but hopefully you get the idea :)

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