【问题标题】:How to style a clicked button in CSS [duplicate]如何在CSS中设置单击按钮的样式[重复]
【发布时间】:2017-05-30 13:38:53
【问题描述】:

我查看了 W3 学校网站 W3Schools,它解释了使用 CSS 设置按钮的样式。我需要在单击时指定按钮样式。什么是伪类选择器?例如悬停按钮是:

.button:hover{ 
}

【问题讨论】:

标签: html css


【解决方案1】:

此按钮最初会显示为黄色。悬停时它会变成橙色。当你点击它时,它会变成红色。我使用 :hover 和 :focus 来调整样式。 (:active 选择器通常用于链接(即<a> 标签))

button{
  background-color:yellow;
}

button:hover{background-color:orange;}

button:focus{background-color:red;}

a {
  color: orange;
}

a.button{
  color:green;
  text-decoration: none;
}

a:visited {
  color: purple;
}

a:active {
  color: blue;
}
<button>
Hover and Click!
</button>
<br><br>

<a href="#">Hello</a><br><br>
<a class="button" href="#">Bye</a>

【讨论】:

  • :active 通常用于链接(即标签)
  • 由于一些常见的库在我看来通常使用.button作为按钮样式的锚链接(我正在查看你的引导程序)并且OP在示例中有.button可能会将其扩展为包括带有:active 的锚部分?即如果他们想要一个按钮,他们应该使用&lt;button&gt;&lt;/button&gt;,但这不是你的错:)
  • @MarkSchultheiss 我实际上并没有注意到在问题中,明确指出,但如果需要按钮,为什么不使用按钮标签?我将编辑答案以包含带有类按钮的链接....
  • 根据 Mozilla 文档,也应该使用 :active 作为按钮。 developer.mozilla.org/en-US/docs/Web/CSS/:active
【解决方案2】:

如果您只是希望在按下鼠标时按钮具有不同的样式,您可以使用 :active 伪类。

.button:active {
}

另一方面,如果您希望样式在单击后保持不变,则必须使用 javascript。

【讨论】:

    【解决方案3】:

    按钮的三种状态

    • 正常:可以这样选择button
    • 悬停:您可以像这样选择button:hover
    • 按下/单击:您可以像这样选择button:active

    正常:

    .button
     {
         //your css
     }
    

    活跃

     .button:active
    {
            //your css
    }
    

    悬停

     .button:hover
    {
            //your css
    }
    

    片段:

    使用:active 设置按钮的活动状态。

    button:active{
       background-color:red;
    }
    &lt;button&gt;Click Me&lt;/button&gt;

    【讨论】:

      【解决方案4】:

      不幸的是,没有 :click 伪选择器。如果你想在点击时改变样式,你应该使用 Jquery/Javascript。它肯定比纯 HTML / CSS 的“hack”更好。但如果你坚持...

      input {
      display: none;
      }
      span {
      padding: 20px;
      font-family: sans-serif;
      }
      input:checked + span {
        background: #444;
        color: #fff;
      }
        <label for="input">
        <input id="input" type="radio" />
        <span>NO JS styling</span>
        </label>

      或者,如果您愿意,可以切换样式:

      input {
      display: none;
      }
      span {
      padding: 20px;
      font-family: sans-serif;
      }
      input:checked + span {
        background: #444;
        color: #fff;
      }
        <label for="input">
        <input id="input" type="checkbox" />
        <span>NO JS styling</span>
        </label>

      【讨论】:

      • 为什么选择复选框和单选类型?不是我脑海中的按钮。
      • @Mark Schultheiss 你不明白,如果你运行代码 sn-ps,也许你会。复选框是隐藏的,但您可以利用 :checked 伪选择器,您必须具有复选框输入才能使用。就像我在帖子中提到的那样,这是一个“黑客”。但是,没有其他纯 CSS/HTML 替代品。
      【解决方案5】:

      button:hover 只是当您将光标移到按钮上时。
      尝试 button:active 代替...也适用于其他元素

      button:active{
        color: red;
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 2010-09-07
        • 1970-01-01
        • 2015-09-19
        • 1970-01-01
        • 2012-08-24
        • 2011-09-17
        相关资源
        最近更新 更多