HTML 切换按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1582717/
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-29 01:04:22  来源:igfitidea点击:

HTML toggle buttons

htmlcoding-style

提问by pupeno

I need to represent a toggle button in HTML. My intention is to do it with a normal input submit button and styling. Any recommendations on how to style a toggle button that is understandable and works more or less in all browsers?

我需要在 HTML 中表示一个切换按钮。我的意图是使用普通的输入提交按钮和样式来完成。关于如何设计易于理解且在所有浏览器中或多或少都能正常工作的切换按钮的样式有什么建议吗?

回答by Dylan Beattie

Since you're representing a single control with a true/false state, you really want to use a checkbox as the underlying form element to maintain compatibility with downlevel browsers, screen readers and so on. One approach here is to associate a label control with the checkbox, and then using a combination of CSS and jQuery to make the actual checkbox itself 'invisible', render the label as a button, and modify the label's border property as the checkbox is checked or unchecked.

由于您使用 true/false 状态表示单个控件,因此您确实希望使用复选框作为底层表单元素,以保持与下层浏览器、屏幕阅读器等的兼容性。这里的一种方法是将标签控件与复选框关联,然后使用 CSS 和 jQuery 的组合使实际的复选框本身“不可见”,将标签呈现为按钮,并在选中复选框时修改标签的边框属性或未选中。

This code works in Chrome, Safari, Opera, Firefox and IE (thanks to a conditional-comment hack since IE treats hidden form elements differently to other browsers). If you submit the enclosing form you get ordinary HTML checkbox behaviour in the resulting form submission.

此代码适用于 Chrome、Safari、Opera、Firefox 和 IE(感谢条件注释黑客,因为 IE 处理隐藏表单元素与其他浏览器不同)。如果您提交封闭表单,您将在结果表单提交中获得普通的 HTML 复选框行为。

   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
      <title>jQuery Toggle Button </title>

     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

      <style type="text/css">
           /* Style the label so it looks like a button */
           label {
                border: 2px outset #cccccc;
                background-color: #cccccc;
                position: relative;
                z-index: 3;
                padding: 4px;
           }
           /* CSS to make the checkbox disappear (but remain functional) */
           label input {
                position: absolute;
                visibility: hidden;
           }
      </style>
      <!--[if IE]>
      /* Conditional styles applied in IE only to work around cross-browser bugs */
       <style>
            label input#myCheckbox {
                visibility: visible;
                z-index: 2;
           }
       </style>
      <![endif]-->

      <script type="text/javascript">
           $(function() {
                $("#toggleCheckbox").click(function() {
                     $(this).closest("label").css({ borderStyle: this.checked ? 'inset' : 'outset' });
                });
           });
      </script>

 </head>
 <body>
      <form action="http://www.w3schools.com/html/html_form_action.asp" method="get">
           <label for="toggleCheckbox">
                <input type="checkbox" name="toggled" id="toggleCheckbox" value="1" />
                Toggled?</label>
           <input type="submit" name="verb" value="Submit Form" />
      </form>
 </body>
 </html>

回答by ebdo

Well i was trying to implement a slider in html using css and javascript. Found few references but they were not completely helpful. So find below my implementation. Part of it is taken from somewhere else in the web tho i dont remember from where. Anyway here it goes: 1>This slider is based on a button that you click.

好吧,我正在尝试使用 css 和 javascript 在 html 中实现一个滑块。找到了很少的参考资料,但它们并不完全有帮助。所以在我的实现下面找到。部分内容取自网络上的其他地方,但我不记得出自何处。无论如何,它是这样的: 1>此滑块基于您单击的按钮。

1>HTML code

1>HTML代码

<div class="SwitchBtn" >                    
    <input type="checkbox" class = "SwitchBtn_Check" id = "checkboxForSwitch" style = "display:none;"/>
    <div class = "transitionSwitch">
        <input type = "button" class = "SwitchBtn_Btn off" id="buttonForSwitch" name = "TurnOn" onclick = "toggleStandBy()" />              
        <div class = "slider_label off" id = "labelForSwitch" >
            <div class = "SwitchBtn_active" id= "btnAct" ><span class = "switchOn">On</span></div>
            <div class = "SwitchBtn_inactive" id= "btnInact" ><span class = "switchOff">Off</span></div>
        </div>
    </div>              
</div>

2>CSS code

2>CSS 代码

/* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@Related to switch button start@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */

.SwitchBtn{
position: relative;         /*this is very important or else precentage used in its child nodes will take effect of the next parent which has anything other than static*/      
overflow: hidden;
height:44.56px;
width:148.10px;


-webkit-box-shadow: 0 0 0 2px rgb(145, 149, 155);       
-moz-box-shadow: 0 0 0 2px rgb(145, 149, 155);
box-shadow: 0 0 0 2px rgb(145, 149, 155);
-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-webkit-user-select:none; 
-moz-user-select:none;  
}

.transitionSwitch{          

overflow: hidden;   
margin-left: 0;
width:100%;
height: 100%;


-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;
-moz-transition: margin 0.3s ease-in 0s; 
-webkit-transition: margin 0.3s ease-in 0s;
transition: margin 0.3s ease-in 0s;
}

.SwitchBtn_Check:checked+ .transitionSwitch{            
margin-left:50%;
}

.slider_label{
position:absolute;
width:150%;
height:100%;        

overflow: hidden;
margin-left:-50%;

-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;

-webkit-box-shadow: 0 0 0 2px rgb(145, 149, 155);           
-moz-box-shadow: 0 0 0 2px rgb(145, 149, 155);
box-shadow: 0 0 0 2px rgb(145, 149, 155);

}

.switchOn
{
position:relative;
top:5.57px;             /*vvvsma half of vvsma i.e. 11.14px*/
left:11.14px;           /*vvsma half of vsma i.e. 22.28px*/

}

.switchOff
{
    position:relative;
    top:5.57px;
    left:11.14px;


}

.SwitchBtn_active{  
position:absolute;
width:50%;
height:100%;    
vertical-align:center;
left:0;
font-weight: normal;
font-family: Avenir, Tahoma, Arial, Verdana;
color: #FCF9F9;
font-size: 26.21px;
text-indent:10px;       

background-image: -moz-linear-gradient(top, #7EA3D5 0%, #5C89C7 50%, #3966B0 51%, #3764AF 100%);
background-image: -webkit-linear-gradient(top, #7EA3D5 0%, #5C89C7 50%, #3966B0 51%, #3764AF 100%);
background-image: -o-linear-gradient(top, #7EA3D5 0%, #5C89C7 50%, #3966B0 51%, #3764AF 100%);
background-image: linear-gradient(top, #7EA3D5 0%, #5C89C7 50%, #3966B0 51%, #3764AF 100%);

-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;     
}

.SwitchBtn_inactive
{   
width:50%;
height:100%;
vertical-align:center;
position:absolute;
right:0;        
font-weight: normal;
font-family: Avenir, Tahoma, Arial, Verdana;
color: #291818;
font-size: 26.21px;
text-indent:45px;


-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px;

background-image: -moz-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: -webkit-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: -o-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);

}

.SwitchBtn_Btn{

width:50%;
height:100%;
position:absolute;
z-index:1;  
margin-left:0;  

-webkit-box-shadow: 0 0 0 0.5px rgb(145, 149, 155);         
-moz-box-shadow: 0 0 0 0.5px rgb(145, 149, 155);
box-shadow: 0 0 0 0.5px rgb(145, 149, 155);

background-image: -moz-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: -webkit-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: -o-linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);
background-image: linear-gradient(top, rgb(236,236,237) 0%, rgb(208,209,211) 50%, rgb(185,187,189) 51%, rgb(190,191,194) 100%);

-webkit-border-radius: 8px;
-moz-border-radius: 8px;
border-radius: 8px; 

}

/* @@@@@@@@@@@@@@@@@@@@@@@Related to switch button End@@@@@@@@@@@@@@@@ */

3>Javascript Code a>The below example is with respect to Ajax

3>Javascript 代码 a>下面的例子是关于 Ajax 的

function toggleStandBy()
{       


        var xmlhttp;
        if(window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest();
        else
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

        xmlhttp.onreadystatechange = function()
        {

            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {       

                if(xmlhttp.responseText == "1")             
                {
                        document.getElementById('checkboxForSwitch').checked = !document.getElementById('checkboxForSwitch').checked;
                }

            }

        }   
        xmlhttp.open("POST","http://192.168.1.x/sample.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        if(document.getElementById('buttonForSwitch').name == "TurnOn")
        {   
            document.getElementById('buttonForSwitch').name = "TurnOff";
            xmlhttp.send("state=1");
        }
        else if(document.getElementById('buttonForSwitch').name == "TurnOff")
        {           
            document.getElementById('buttonForSwitch').name = "TurnOn";
            xmlhttp.send("state=0");
        }
}

a>The below is a simple example

a>下面是一个简单的例子

function toggleStandBy()
{    
     if(document.getElementById('buttonForSwitch').name == "TurnOn")
     {  
          document.getElementById('buttonForSwitch').name = "TurnOff";
            }
      else if(document.getElementById('buttonForSwitch').name == "TurnOff")
      {         
                document.getElementById('buttonForSwitch').name = "TurnOn";
       }
    document.getElementById('checkboxForSwitch').checked = !document.getElementById('checkboxForSwitch').checked;

   } 

The images of how the button appears is as below

按钮出现的图像如下

Off buttonOn buttonToggle slide

关闭按钮开启按钮切换幻灯片

The appearance changes a tiny winy bit based on the browser.(Obviously dont get expect it to look completely proper on IE. If you remove gradient and put normal colors it will work in IE as well OR "just add background-color: property along with background-image: in CSS and since IE takes background-color: and does not support background-image: your reqd background color will be shown without the need for any particular browser sepcification implementations")

外观会根据浏览器而改变一点点。(显然不要期望它在 IE 上看起来完全正确。如果您删除渐变并放置正常颜色,它也可以在 IE 中使用,或者“只需添加 background-color: 属性使用 background-image: 在 CSS 中,并且由于 IE 采用 background-color: 并且不支持 background-image:您的 reqd 背景颜色将被显示,而无需任何特定的浏览器 sepcification 实现")

回答by brennanyoung

All browsersyou say? In that case, however you choose to represent it visually, be sure to use aria-pressedso the toggle state is exposed to the accessibility API (and thus assistive technology). One nice thing about this is that you can then use this attribute in a CSS selector such as

你说的所有浏览器?在这种情况下,无论您选择如何以视觉方式表示它,请务必使用,aria-pressed以便将切换状态公开给可访问性 API(以及辅助技术)。关于这一点的一件好事是,您可以在 CSS 选择器中使用此属性,例如

button[aria-pressed="true"] {
    border: 2px solid #000;
}

That will save you having to come up with a class name - there's a standard one!

这将使您不必想出一个类名——有一个标准的名称!

n.b. strictly speaking, the aria-pressedattribute should only be used with <button>elements, or elements with role=button

nb 严格来说,该aria-pressed属性应该只与<button>元素一起使用,或者带有role=button