开发者

Change button background-color on clicking itself

开发者 https://www.devze.com 2023-03-19 07:48 出处:网络
Let\'s say I have #button with a given background-image:url开发者_运维知识库(images/some_background) and I want to change it to another background when I click it, let\'s say url(images/other_backgrou

Let's say I have #button with a given background-image:url开发者_运维知识库(images/some_background) and I want to change it to another background when I click it, let's say url(images/other_background).

        HTML

         <a id="button" ></a> 

        CSS

     display: block; 
     height:100px;
     width:100px;
     background-image:url(images/other_background.png)

I tried this, but it doesnt work :

    $(document).ready(function(){

    $('#button').click(function(){

            $('#button').css('backgroundImage', 'url(images/other_background.png)');

        });

});


This works for me

CSS

#button{display: block; height:100px; width:100px;  
background-image:url(http://cheeptalk.files.wordpress.com/
2009/05/smurfs-hefty-smurf-100x100.png?w=96&h=96); border:1px solid red;}

border to see easier only

code

$('#button').click(function(){
    $(this).css('backgroundImage','url(http://images.mirror.co.uk/upl/m4/\
    feb2010/9/3/mr-t-100x100-938742195.jpg)');
});

http://jsfiddle.net/jasongennaro/Lvnmw/

Obviously, you will need to switch out the images for your own.

If you are having trouble, check

  1. That you are calling the jQuery script first, before this script.

  2. That the path to your images is correct.


alittle off-topic, but you should consider using sprites instead of 2 completely seperate images.

Why? Becuase for slower connections and on certain browsers, the click event will cause a 'flicker' as the new image is being downloaded then loaded. Sprites will gaurentee the image is already loaded and so you just need to change the background-position to 'load' the new image.


Try this:

$("#button").css("background-image", "url(/images/otherbackground.png)");

OR

$(this).css("background-image", "url(/images/otherbackground.png)");

0

精彩评论

暂无评论...
验证码 换一张
取 消