Toggling background position on click

2019-07-09 03:42发布

问题:

I am trying to achieve this Is there an easy way to toggle background position between two states on click event?

I have constructed a function that should work.. haven't got a clue why it won't. I have spent a number of hours trying to achieve this for such a tedious part of my project, but it's necessary.

Please take a look at this function:

$("#secondarrow").click(function(){
    /*$(".arrows").toggle( 
    function(){ 
        $(this).css({"background-position":"0px 0px"}); 
    },  
    function(){ 
        $(this).css({"background-position":"0px -30px"}); 
    });*/
    /*$(".arrows").toggleClass(function() {
    if ($(this).is(".arrows")) {
    return ".arrowsup";
    } else {
    return ".arrows";
    }
    });*/
    $('#secondarrow').toggle(function() { 
    $("#arrow2").css('backgroundPosition', '0px -15px'); 
    }, function() { 
    $("#arrow2").css('backgroundPosition', '0px 0px'); 
    });
$("#ukmore").slideToggle(100);
$("#clause").slideToggle(100);
});

What it should do is, on clicking the div name second arrow, it reveals a number of sub-categories and at the same time toggle the background position of a div child with the id #arrow2 from an arrow that's pointing down (to indicate click to reveal more) to an arrow that's pointing up which is part of the same background image (to indicate click to hide sub-categories).

I have tried a number of different function structures but none of them are working as required, the latest one - the one that isn't commented out - does change the background position to show the arrow pointing up but it only does it the on the first click AND only does it when clicking directly on the #arrow1 div, when I need it to toggle back and forth on clicking the #secondarrow div.

Please help.

回答1:

First of all - you need to practise handling events a bit more.

.toggle is also an event handler, so you basically add a new click handler for toggling when the item is clicked.

You only need to do something like this:

$("#secondarrow").toggle(function() { 
    $("#arrow2").css('backgroundPosition', '0px -15px');
    //do more stuff on first click
    }, function() { 
    $("#arrow2").css('backgroundPosition', '0px 0px'); 
    //do more stuff on second click
    });

I can't check if the above will work for you. I recommend putting your code in jsFiddle for stackoverflow question too.

Second thing

It is better to create a css class with the second position and then bind a click event in which you toggle the class:

$("#secondarrow").click(function(){
   $("#arrow2").toggleClass('position2');
})

And a tip:

Use firebug or chrome developer tools to debug your code. You can check if your selector was correct. Also,read about selector caching, eg. $element=$('.something'); $element.show()