jQuery 你如何创建一个切换按钮?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/309081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:56:04  来源:igfitidea点击:

How do you create a toggle button?

jqueryhtmlcss

提问by Donny V.

I want to create a toggle button in html using css. I want it so that when you click on it , it stays pushed in and than when you click it on it again it pops out.

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

If theres no way of doing it just using css. Is there a way to do it using jQuery?

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

采纳答案by alexmeia

The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

好的语义方式是使用复选框,然后如果选中或未选中它,则以不同的方式对其进行样式设置。但是没有什么好的方法可以做到。您必须添加额外的跨度、额外的 div,并且为了看起来非常漂亮,添加一些 javascript。

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:

所以最好的解决方案是使用一个小的 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>

Obviously, you can add background images that represent button up and button down, and make the background color transparent.

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

回答by bkdraper

JQuery UI makes light work out of creating toggle buttons. Just put this

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

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

on your page and then in your body onLoador your $.ready()(or some object literals init()function if your building an ajax site..) drop some JQuery like so:

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

$("#myToggleButton").button()

thats it. (don't forget the < label for=...>because JQueryUI uses that for the body of the toggle button..)

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

From there you just work with it like any other input="checkbox" because that is what the underlying control still is but JQuery UI just skins it to look like a pretty toggle button on screen.

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

回答by suhailvs

here is an example using pure css:

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

回答by Pierre de LESPINAY

In combination with thisanswer, you can also use this kind of style that is like mobile settings toggler.

结合答案,您还可以使用这种类似于移动设置切换器的样式。

togglers

切换器

HTML

HTML

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

CSS

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

jQuery

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

Could be much prettier, but gives the idea.
One advantage is that it can be animated with jquery and/or CSS3
Fiddler

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

回答by monkey do

If you want a proper button then you'll need some javascript. Something like this (needs some work on the styling but you get the gist). Wouldn't bother using jquery for something so trivial to be honest.

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

回答by tim

You can just use toggleClass()to track state. Then you check if button element has the class, like this:

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

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

And I use the buttonelement for buttons for semantic reasons.

button出于语义原因,我将元素用于按钮。

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

回答by Titouan de Bailleul

I don't think using JS for creating a button is good practice. What if the user's browser deactivates JavaScript ?

我不认为使用 JS 来创建按钮是好的做法。如果用户的浏览器停用 JavaScript 会怎样?

Plus, you can just use a checkbox and a bit of CSS to do it. And it easy to retrieve the state of your checkbox.

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

This is just one example, but you can style it how want.

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

http://jsfiddle.net/4gjZX/

http://jsfiddle.net/4gjZX/

HTML

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

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;
}?

Hope this helps

希望这可以帮助

回答by anand.trex

You could use an anchor element (<a></a>), and use a:active and a:link to change the background image to toggle on or off. Just a thought.

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

Edit: The above method doesn't work too well for toggle. But you don't need to use jquery. Write a simple onClick javascript function for the element, which changes the background image appropriately to make it look like the button is pressed, and set some flag. Then on next click, image and flag is is reverted. Like so

编辑:上述方法对于切换效果不太好。但是你不需要使用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;
}
}

And the html like so <div id="toggleDiv" onclick="toggle()">Some thing</div>

和 html 一样 <div id="toggleDiv" onclick="toggle()">Some thing</div>

回答by Galwegian

I would be inclined to use a class in your css that alters the border style or border width when the button is depressed, so it gives the appearance of a toggle button.

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

回答by Nickolay

There's a jquery plugin by Swizec, which can do this among other things: https://github.com/Swizec/styled-button

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

(The old link was http://swizec.com/code/styledButton/, I didn't fully test the replacement, just found it w/Google.)

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