HTML切换按钮

我需要在 HTML中表示切换按钮.我的意图是使用正常的输入提交按钮和样式.关于如何设置切换按钮的样式的任何建议都是可以理解的,并且在所有浏览器中或多或少都有效?

解决方法

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

代码适用于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>

相关文章

Mip是什么意思以及作用有哪些
怎么测试Mip页面运行情况
MIP安装的具体步骤有哪些
HTML添加超链接、锚点的方法及作用详解(附视频)
MIP的规则有哪些
Mip轮播图组件中的重要属性讲解