如何切换jQuery插件?

时间:2016-05-16 20:24:24

标签: jquery jquery-plugins toggle

我有一个问题。如何使用按钮切换jQuery插件。所以举个例子。让我们说我制作了一个插件,将所有<div>元素变为红色。如何设置按钮,当我单击它时,它会将所有<div>元素变为红色,当我再次单击它时它会反转效果?如果您需要更多信息,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:0)

在元素中添加和删除CSS类是一种方法:

CSS

.red{
background-color:red;
}

HTML

     <button id="toggleButton">Click Me!</button>

JS&amp; JQUERY

        var toggle=0;  //Start with the toggle state as off

        function toggleRed(){

          if (toggle===0){
          $('div').addClass("red"); //add the class 'red' to all divs
          toggle=1;  //Save the toggle state as on until the next click

          }else{

          $('div').removeClass("red"); //remove the class 'red' from all divs
          toggle=0; //Save the toggle state as off until the next click

          }
        }

        $("#toggleButton").click(function{toggleRed()});//attach event handler to button

或者做JS / JQUERY的简短方法:

    $("#toggleButton").click(function{
     $( "div" ).toggleClass( "red" );
    })