【问题标题】:How do you create a toggle button?你如何创建一个切换按钮?
【发布时间】:2010-09-23 11:18:41
【问题描述】:

我想使用 css 在 html 中创建一个切换按钮。我想要它,这样当您单击它时,它会保持在推入状态,而当您再次单击它时,它会弹出。

如果没有办法只使用 css。有没有办法使用jQuery来做到这一点?

【问题讨论】:

标签: jquery html css


【解决方案1】:

良好的语义方式是使用复选框,然后以不同的方式设置它是否被选中。但是没有好的方法可以做到这一点。您必须添加额外的 span、额外的 div,并且为了看起来非常漂亮,添加一些 javascript。

所以最好的解决方案是使用一个小的 jQuery 函数和两个背景图像来设置按钮的两种不同状态的样式。具有由边框给出的上/下效果的示例:

$(document).ready(function() {
  $('a#button').click(function() {
    $(this).toggleClass("down");
  });
});
a {
  background: #ccc;
  cursor: pointer;
  border-top: solid 2px #eaeaea;
  border-left: solid 2px #eaeaea;
  border-bottom: solid 2px #777;
  border-right: solid 2px #777;
  padding: 5px 5px;
}

a.down {
  background: #bbb;
  border-top: solid 2px #777;
  border-left: solid 2px #777;
  border-bottom: solid 2px #eaeaea;
  border-right: solid 2px #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="button" title="button">Press Me</a>

显然,您可以添加代表按钮向上和按钮向下的背景图像,并使背景颜色透明。

【讨论】:

  • 这是一个 JS fiddle 这段代码,所以你可以现场试用...jsfiddle.net/LmULE
  • 仅供参考:我和这篇文章做了同样的事情,只使用了 Google Dart steelpinjata.com/2014/03/20/toggle-buttons-in-dart。注意:在 Chromium 中工作,但可以编译为 JavaScript,并且可以在其他现代浏览器中工作。 IE 不算作浏览器 ;-)
【解决方案2】:

JQuery UI 使创建切换按钮的工作变得轻松。放这个

<label for="myToggleButton">my toggle button caption</label>
<input type="checkbox" id="myToggleButton" />

在您的页面上,然后在您的正文中 onLoad 或您的 $.ready()(或一些对象文字 init() 函数,如果您构建一个 ajax 站点..)像这样删除一些 JQuery:

$("#myToggleButton").button()

就是这样。 (不要忘记&lt; label for=...&gt;,因为 JQueryUI 使用它作为切换按钮的主体..)

从那里您可以像使用任何其他 input="checkbox" 一样使用它,因为这仍然是底层控件,但 JQuery UI 只是将它的皮肤看起来像屏幕上的一个漂亮的切换按钮。

【讨论】:

  • 鉴于 OP 添加了 jquery 标签,这是一个很好的答案。鉴于 jqueryUI 可用于提供一致的样式。
【解决方案3】:

这里是一个使用pure css的例子:

  .cmn-toggle {
    position: absolute;
    margin-left: -9999px;
    visibility: hidden;
  }
  .cmn-toggle + label {
    display: block;
    position: relative;
    cursor: pointer;
    outline: none;
    user-select: none;
  }
  input.cmn-toggle-round + label {
    padding: 2px;
    width: 120px;
    height: 60px;
    background-color: #dddddd;
    border-radius: 60px;
  }
  input.cmn-toggle-round + label:before,
  input.cmn-toggle-round + label:after {
    display: block;
    position: absolute;
    top: 1px;
    left: 1px;
    bottom: 1px;
    content: "";
  }
  input.cmn-toggle-round + label:before {
    right: 1px;
    background-color: #f1f1f1;
    border-radius: 60px;
    transition: background 0.4s;
  }
  input.cmn-toggle-round + label:after {
    width: 58px;
    background-color: #fff;
    border-radius: 100%;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    transition: margin 0.4s;
  }
  input.cmn-toggle-round:checked + label:before {
    background-color: #8ce196;
  }
  input.cmn-toggle-round:checked + label:after {
    margin-left: 60px;
  }
<div class="switch">
  <input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round" type="checkbox">
  <label for="cmn-toggle-1"></label>
</div>

【讨论】:

    【解决方案4】:

    结合this的回答,你也可以使用这种类似手机设置切换器的样式。

    HTML

    <a href="#" class="toggler">&nbsp;</a>
    <a href="#" class="toggler off">&nbsp;</a>
    <a href="#" class="toggler">&nbsp;</a>
    

    CSS

    a.toggler {
        background: green;
        cursor: pointer;
        border: 2px solid black;
        border-right-width: 15px;
        padding: 0 5px;
        border-radius: 5px;
        text-decoration: none;
        transition: all .5s ease;
    }
    
    a.toggler.off {
        background: red;
        border-right-width: 2px;
        border-left-width: 15px;
    }
    

    jQuery

    $(document).ready(function(){
        $('a.toggler').click(function(){
            $(this).toggleClass('off');
        });
    });
    

    可能更漂亮,但给出了这个想法。
    一个优点是它可以用 CSS 动画
    Fiddler

    【讨论】:

      【解决方案5】:

      如果您想要一个合适的按钮,那么您需要一些 javascript。像这样的东西(需要在样式上做一些工作,但你明白了要点)。老实说,不会为如此微不足道的事情而烦恼使用 jquery。

      <html>
      <head>
      <style type="text/css">
      .on { 
      border:1px outset;
      color:#369;
      background:#efefef; 
      }
      
      .off {
      border:1px outset;
      color:#369;
      background:#f9d543; 
      }
      </style>
      
      <script language="javascript">
      function togglestyle(el){
          if(el.className == "on") {
              el.className="off";
          } else {
              el.className="on";
          }
      }
      </script>
      
      </head>
      
      <body>
      <input type="button" id="btn" value="button" class="off" onclick="togglestyle(this)" />
      </body>
      </html>
      

      【讨论】:

        【解决方案6】:

        您可以只使用toggleClass() 来跟踪状态。然后检查按钮元素是否具有类,如下所示:

        $("button.toggler").click( function() {
            $me = $(this);
            $me.toggleClass('off');
            if($me.is(".off")){
                alert('hi');
            }else {
                alert('bye');
            }
        });
        

        出于语义原因,我使用button 元素作为按钮。

        <button class="toggler">Toggle me</button>
        

        【讨论】:

          【解决方案7】:

          您可以使用锚元素 (&lt;a&gt;&lt;/a&gt;),并使用 a:active 和 a:link 更改背景图像以打开或关闭。只是一个想法。

          编辑:上述方法对切换效果不太好。但是你不需要使用 jquery。为元素编写一个简单的 onClick javascript 函数,它会适当地更改背景图像以使其看起来像按钮被按下,并设置一些标志。然后在下一次单击时,图像和标志被还原。像这样

          var flag = 0;
          function toggle(){
          if(flag==0){
              document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img1.gif";
              flag=1;
          }
          else if(flag==1){
              document.getElementById("toggleDiv").style.backgroundImage="path/to/img/img2.gif";
              flag=0;
          }
          }
          

          而 html 就像这样 &lt;div id="toggleDiv" onclick="toggle()"&gt;Some thing&lt;/div&gt;

          【讨论】:

            【解决方案8】:

            我倾向于在你的 css 中使用一个类,当按钮被按下时改变边框样式或边框宽度,所以它给出了一个切换按钮的外观。

            【讨论】:

              【解决方案9】:

              我不认为使用 JS 创建按钮是一种好习惯。如果用户的浏览器停用 JavaScript 怎么办?

              另外,您可以只使用一个复选框和一些 CSS 来做到这一点。 并且很容易检索您的复选框的状态。

              这只是一个示例,但您可以根据需要设置样式。

              http://jsfiddle.net/4gjZX/

              HTML

              <fieldset class="toggle">
                <input id="data-policy" type="checkbox" checked="checked" />
                <label for="data-policy">
                <div class="toggle-button">
                  <div class="toggle-tab"></div>
                </div>
                Toggle
                </label>
              </fieldset>​
              

              CSS

              .toggle label {
                color: #444;
                float: left;
                line-height: 26px;
              }
              .toggle .toggle-button {
                margin: 0px 10px 0px 0px;
                float: left;
                width: 70px;
                height: 26px;
                background-color: #eeeeee;
                background-image: -webkit-gradient(linear, left top, left bottom, from(#eeeeee), to(#fafafa));
                background-image: -webkit-linear-gradient(top, #eeeeee, #fafafa);
                background-image: -moz-linear-gradient(top, #eeeeee, #fafafa);
                background-image: -o-linear-gradient(top, #eeeeee, #fafafa);
                background-image: -ms-linear-gradient(top, #eeeeee, #fafafa);
                background-image: linear-gradient(top, #eeeeee, #fafafa);
                filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#eeeeee', EndColorStr='#fafafa');
                border-radius: 4px;
                -webkit-border-radius: 4px;
                -moz-border-radius: 4px;
                border: 1px solid #D1D1D1;
              }
              .toggle .toggle-button .toggle-tab {
                width: 30px;
                height: 26px;
                background-color: #fafafa;
                background-image: -webkit-gradient(linear, left top, left bottom, from(#fafafa), to(#eeeeee));
                background-image: -webkit-linear-gradient(top, #fafafa, #eeeeee);
                background-image: -moz-linear-gradient(top, #fafafa, #eeeeee);
                background-image: -o-linear-gradient(top, #fafafa, #eeeeee);
                background-image: -ms-linear-gradient(top, #fafafa, #eeeeee);
                background-image: linear-gradient(top, #fafafa, #eeeeee);
                filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#fafafa', EndColorStr='#eeeeee');
                border: 1px solid #CCC;
                margin-left: -1px;
                margin-top: -1px;
                border-radius: 4px;
                -webkit-border-radius: 4px;
                -moz-border-radius: 4px;
                -webkit-box-shadow: 5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
                -moz-box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
                box-shadow: 5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
              }
              .toggle input[type=checkbox] {
                display: none;
              }
              .toggle input[type=checkbox]:checked ~ label .toggle-button {
                background-color: #2d71c2;
                background-image: -webkit-gradient(linear, left top, left bottom, from(#2d71c2), to(#4ea1db));
                background-image: -webkit-linear-gradient(top, #2d71c2, #4ea1db);
                background-image: -moz-linear-gradient(top, #2d71c2, #4ea1db);
                background-image: -o-linear-gradient(top, #2d71c2, #4ea1db);
                background-image: -ms-linear-gradient(top, #2d71c2, #4ea1db);
                background-image: linear-gradient(top, #2d71c2, #4ea1db);
                filter: progid:dximagetransform.microsoft.gradient(GradientType=0, StartColorStr='#2d71c2', EndColorStr='#4ea1db');
              }
              .toggle input[type=checkbox]:checked ~ label .toggle-button .toggle-tab {
                margin-left: 39px;
                -webkit-box-shadow: -5px 0px 4px -5px #000000, 0px 0px 0px 0px #000000;
                -moz-box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
                box-shadow: -5px 0px 4px -5px rgba(0, 0, 0, 0.3), 0px 0px 0px 0px #000000;
              }​
              

              希望对你有帮助

              【讨论】:

                【解决方案10】:

                试试这个:

                input type="button" 
                                           data-bind="css:{on:toggleButton, off:toggleButton!=true},value:toggleButton,click: function() { $data.toggleButton(!($data.toggleButton()))}" />
                
                in viewModel
                self.toggleButton = ko.observable(false);
                

                【讨论】:

                  【解决方案11】:

                  Swizec 有一个 jquery 插件,它可以做到这一点:https://github.com/Swizec/styled-button

                  (旧链接是http://swizec.com/code/styledButton/,我没有完全测试替换,只是用谷歌找到了。)

                  【讨论】:

                    【解决方案12】:

                    采用极简方法的纯 CSS

                    您只需要一个带有背景作为滑块的复选框。结果是可以使用键盘和屏幕阅读器。

                    input {
                      appearance: none;
                      padding: 16px 30px;
                      border-radius: 16px;
                      background: radial-gradient(circle 12px, white 100%, transparent calc(100% + 1px)) #ccc -14px;
                      transition: 0.3s ease-in-out;
                    }
                    
                    :checked {
                      background-color: dodgerBlue;
                      background-position: 14px;
                    }
                    &lt;input type="checkbox"&gt;

                    另见

                    How to add the text "ON" and "OFF" to toggle button

                    【讨论】:

                      【解决方案13】:

                      您可以使用“活动”伪类(但它不适用于 IE6,但对于链接以外的元素)

                      a:active
                      {
                          ...desired style here...
                      }
                      

                      【讨论】:

                        【解决方案14】:

                        这里是使用 jQuery 和 &lt;label for="input"&gt; 实现的 ToggleButton 的示例/变体(更详细描述)之一。

                        首先,我们将使用经典 HTML &lt;input&gt;&lt;label&gt; 为 ToggleButton 创建容器

                        <span>
                          <input type="checkbox" value="1" name="some_feature_to_select" id="feature_cb" style="display: none;"> <!-- We can hide checkbox bec. we want <label> to be a ToggleButton, so we don't need to show it. It is used as our value holder -->
                          <label for="feature_cb" id="label_for_some_feature">
                            <img alt="Stylish image" src="/images/icons/feature.png">
                          </label>
                        </span>
                        

                        接下来我们将定义用于切换按钮的函数。我们的按钮实际上是通常的&lt;label&gt;,我们将对其进行样式设置以表示值切换。

                        function toggleButton(button) {
                        
                        var _for = button.getAttribute('for'); // defining for which element this label is (suppose element is a checkbox (bec. we are making ToggleButton ;) )
                        var _toggleID = 'input#'+_for; // composing selector ID string to select our toggle element (checkbox)
                        var _toggle = $( _toggleID ); // selecting checkbox to work on
                        var isChecked = !_toggle.is(':checked'); // defining the state with negation bec. change value event will have place later, so we negating current state to retrieve inverse (next).
                        
                        if (isChecked)
                            $(button).addClass('SelectedButtonClass'); // if it is checked -> adding nice class to our button (<label> in our case) to show that value was toggled
                        else
                            $(button).removeClass('SelectedButtonClass'); // if value (or feature) was unselected by clicking the button (<label>) -> removing .SelectedButtonClass (or simply removing all classes from element)
                        }
                        

                        函数以可重用的方式实现。您可以将它用于您创建的多个、两个甚至三个 ToggleButtons。

                        ...最后...为了使其按预期工作,我们应该将切换功能绑定到我们即兴的&lt;label&gt;按钮的事件(“更改”事件)(它将是click事件bec。我们不会直接更改checkbox,因此不能为&lt;label&gt; 触发change 事件。

                        $(document).ready(function(){
                        
                            $("#some_feature_label").click(function () {
                                toggleButton(this); // call function with transmitting instance of a clicked label and let the script decide what was toggled and what to do with it
                            });
                        
                            $("#some_other_feature_label").click(function () {
                                toggleButton(this); // doing the same for any other feature we want to represent in a way of ToggleButton
                            });
                        
                        });
                        

                        通过 CSS,我们可以定义 backgorund-image 或一些 border 来表示值的变化,而 &lt;label&gt; 将为我们完成更改复选框值的工作;)。

                        希望这对某人有所帮助。

                        【讨论】:

                        • + 这个实现似乎在移动设备上也能正常工作,bec。上面由 TDeBailleul 提出的 CCS 实现在 Android 上无法正常工作(Android 2.3.5 默认浏览器;同一系统上的 Opera Mobile 还可以)。
                        • 另外,您可以使用.toggleClass(),而不是.addClass()/.removeClass(),但所描述的方法明确定义了checked/unchecked值的操作。
                        【解决方案15】:

                        试试;

                        <li>Text To go with Toggle Button<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'somename' id = 'someid' /></span></li>
                        

                        并确保在

                        <head><link rel = 'stylesheet' src = 'theme.css'> (from jqtouch - downloadable online)
                              <link rel = 'text/javascript' src = 'jquery.js'> (also from jqtouch)
                        </head>
                        

                        请记住,当您编写此代码时,只有 somenamesomeid 可以在输入标签中更改,否则不起作用。

                        【讨论】:

                          【解决方案16】:

                          据我所知,我也在寻找答案,并想用 CSS 来完成它。我找到了 CSS NINJA 的解决方案 这是 &lt;input type="checkbox"&gt; 和一些 css 的一个很好的实现 Live demo! 虽然它在 IE 8 中不起作用,但您可以实现 selectivizr!并修复 CSS where using opacity to filter 使其在 IE 中工作。

                          2014 年编辑:

                          对于新的切换按钮,我确实使用在 Lea Verou blog 上找到的解决方案,视觉上类似于 iOS 复选框

                          【讨论】:

                            【解决方案17】:

                            以下方式只依赖html-css,不需要任何js。

                            css 和 HTML sn-p 就这么简单:

                            #mycbid
                            {
                              display:none;
                            }
                            
                            #mycbid:checked + #mylabelid
                            {
                              background: grey;
                              border: inset;
                            }
                            
                            #mylabelid
                            {
                              background: lightgray;
                              border: outset;
                            }
                            <input type="checkbox" id="mycbid">
                              <label for="mycbid" id="mylabelid">Text of the label</label>

                            说明:

                            在引擎盖下不会显示复选框,但仍可以将其设置为选中或未选中,因此可以或多或少地像往常一样使用它。

                            当复选框被选中时,其状态“触发”#mycbid:checked + #mylabelid 下的 css 规则,并且标签将相应地设置样式。这个 css 选择器实际上是一切的关键:实际上它选择了复选框的 sibling(即它自己的标签)。由于 for 属性,即使未显示复选框,标签也会将点击重定向到复选框。

                            当复选框未被选中时,其状态“触发”#mylabelid 下的 css 规则,标签将相应地设置样式。

                            当然,可以用多种不同的方式设置标签的样式。

                            【讨论】:

                              猜你喜欢
                              • 2014-06-02
                              • 1970-01-01
                              • 1970-01-01
                              • 1970-01-01
                              • 2016-03-05
                              • 2016-04-04
                              • 2013-12-27
                              • 2021-06-02
                              • 1970-01-01
                              相关资源
                              最近更新 更多