简体   繁体   English

反向onClick事件onClick

[英]Reverse onClick Event onClick

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? 有谁知道如何将onClick分配给执行一项操作的对象,然后当用户单击同一对象时,该操作被撤消?

$('#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. 因此,单击#image会将更改添加到#foo或撤消更改。

Fiddle: http://jsfiddle.net/Sx5yH/804/ 小提琴: http : //jsfiddle.net/Sx5yH/804/

Any suggestions? 有什么建议么?

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: active类的定义如下:

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

Demo: http://jsfiddle.net/Sx5yH/812/ 演示: http //jsfiddle.net/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. 然后,您可以使用jquery切换功能来添加/删除样式。

CSS 的CSS

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

JavaScript 的JavaScript

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

http://jsfiddle.net/gb0udnft/1/ http://jsfiddle.net/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 您还可以使用固有的JQuery toggle()函数

http://jsfiddle.net/gb0udnft/2/ http://jsfiddle.net/gb0udnft/2/

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

or use a css class back and forth by using .toggleClass(), .addClass(), or .removeClass() 或通过使用.toggleClass()、. addClass()或.removeClass()来回使用CSS类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM