如何创建切换按钮?


98

我想使用CSS在html中创建一个切换按钮。我想要它,以便当您单击它时,它保持推入状态,而不是再次单击时它弹出。

如果没有办法只使用css。有没有办法使用jQuery?


我写了一个教程,介绍如何仅使用CSS3创建开/关开关,而无需使用JS。在这里您可以看到演示
Felix Hagspiel

Answers:


87

良好的语义方法是使用复选框,然后如果未选中,则以不同的方式设置其样式。但是没有好的方法可以做到这一点。您必须添加额外的跨度,额外的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>

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


17
这是此代码的JS小提琴,因此您可以现场试用... jsfiddle.net/LmULE
Evan

仅供参考:我只使用Google Dart steelpinjata.com/2014/03/20/toggle-buttons-in-dart来完成与该帖子相同的操作。注意:可以在Chromium中使用,但可以编译为JavaScript,并可以在其他现代浏览器中使用。IE不算作浏览器;-)
Serge Merzliakov 2014年

50

jQuery UI使创建切换按钮变得轻而易举。放这个

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

在您的页面上,然后在您的身体onLoad或您的$.ready()(或一些对象文字init()函数,如果您正在构建ajax网站..)中放一些JQuery,如下所示:

$("#myToggleButton").button()

而已。(不要忘记,< label for=...>因为JQueryUI将它用作切换按钮的主体。)

从那里开始,您就可以像其他任何input="checkbox控件一样使用它,因为这仍然是基础控件,但是JQuery UI只是将其外观化为看起来像屏幕上漂亮的切换按钮。


鉴于OP添加了jquery标签,这是一个很好的答案。给定的jqueryUI可用于提供一致的样式。
乔·约翰斯顿

28

这是一个使用示例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>


19

结合答案,您还可以使用这种样式,例如移动设置切换器。

拨动开关

的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');
    });
});

可能更漂亮,但给出了主意。
一个优点是可以使用jquery和/或CSS3 Fiddler对其进行动画处理


7

如果您想要一个合适的按钮,那么您将需要一些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>

4

您可以只使用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>

3

您可以使用锚元素(<a></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 <div id="toggleDiv" onclick="toggle()">Some thing</div>


3

我认为使用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;
}​

希望这可以帮助


2

我倾向于在您的CSS中使用一个类,该类在按下按钮时会更改边框样式或边框宽度,因此它会显示切换按钮的外观。


1

试试这个:

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);


0

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

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

0

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

首先,我们将使用经典的HTML为ToggleButton创建容器<input><label>

<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>

接下来,我们将定义用于切换按钮的功能。实际上,我们的按钮是<label>我们惯常使用的样式,用来表示值切换。

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)
}

功能以可重用的方式实现。您可以将其用于创建的一个以上,两个甚至三个ToggleButton。

...最后,为了使它按预期工作,我们应该将切换功能绑定到我们即兴<label>按钮的事件(“更改”事件)(这是click事件,因为我们不会checkbox直接更改,因此没有change事件)可以解雇<label>)。

$(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-imageborder代表值的变化,同时<label>为我们完成更改复选框的值;)。

希望这对某人有帮助。


+该实现似乎也可以在移动设备上正常运行,因为。TDeBailleul上面建议的CCS实施在Android上无法正常工作(Android 2.3.5默认浏览器;同一系统上的Opera Mobile可以)。
Paul T. Rawkeen

另外,可以使用代替.addClass()/ ,但是所描述的方法显式定义了/ 值的操作。.removeClass().toggleClass()checkedunchecked
Paul T. Rawkeen

0

尝试;

<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可以在输入标签改变,否则这是行不通的。


0

就我也在寻找答案而言,我想用CSS完成它。我通过CSS NINJA找到了解决方案,这是一个不错的实现,<input type="checkbox">还提供了一些CSS Live演示!尽管它在IE 8中不起作用,但您可以实现selectivizr!并修复CSS opacity用于filter使其在IE浏览器。

编辑2014:

对于新的切换按钮,我确实使用Lea Verou博客上找到的解决方案,其外观类似于iOS复选框

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.