最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reverse onClick Event onClick - Stack Overflow

programmeradmin4浏览0评论

Does anyone know how to assign an onClick to an object that performs one action, then when the user clicks on the same object, the action is reversed?

$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

So clicking on #image will either add the changes to #foo or reverse changes.

Fiddle: /

Any suggestions?

Does anyone know how to assign an onClick to an object that performs one action, then when the user clicks on the same object, the action is reversed?

$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

So clicking on #image will either add the changes to #foo or reverse changes.

Fiddle: http://jsfiddle/Sx5yH/804/

Any suggestions?

Share Improve this question asked Apr 6, 2015 at 21:51 KingAlfredChameleonKingAlfredChameleon 4071 gold badge6 silver badges18 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Don't manipulate with inline styles directly, this is not very flexible approach. Instead you want to toggle class that holds necessary styles:

$('#image').click(function() {
    $('#foo').toggleClass('active');
});

where the class active is defined like this:

#foo.active {
    background-color: red;
    color: white;
    font-size: 44px;
}

Demo: http://jsfiddle/Sx5yH/812/

Specifically in your case - it is better to assign a class to the object. Then you can use the jquery toggle functionality to add/remove the style.

CSS

#image.selected {
       background-color: red;
       color: white;
       font-size: 44px;
}

JavaScript

$('#image').click(function() {
    $('#image').toggleClass("selected");
});

http://jsfiddle/gb0udnft/1/

You can use a boolean value to determine whether or not it's been clicked, then use a ternary statement to do whatever depending if it's true or false.

(boolean) ? true : false;

You could also use the innate JQuery toggle() function

http://jsfiddle/gb0udnft/2/

    $('#image').toggle(function() {
    // do whatever 
       }
      , function() {
       // do whatever
});

or use a css class back and forth by using .toggleClass(), .addClass(), or .removeClass()

发布评论

评论列表(0)

  1. 暂无评论