繁体   English   中英

单击按钮时文本更改问题(仅使用 CSS)

[英]When button is clicked text changing issue(Only using CSS)

我试图在单击按钮时将“单击”按钮的change text为“单击”。 此外,当单击按钮时,整个按钮的background color和按钮文本应更改为绿色, border color应更改为红色。

我试图解决这个问题,但我无法实现。

 body{ background-color:#7a86cb; } .center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .button-btn #btn1 ,#btn2, #btn3{ width:120px; height:45px; border-radius:30px; background-color:rgba(0, 0, 0, 0.1); border:2px solid black; color:white; } #btn1{ } #btn2{ margin-left:15px; } #btn3{ margin-left:15px; } .button-btn #btn1:hover,#btn2:hover,#btn3:hover{ background-color:#7a86cb; } .btn1:active,.btn2:active,.btn3:active { background-color: red; transform: translateY(4px); } .btn1:after{ content:"Clicked!"; background-color:green; border:red; }
 <body> <div class="center"> <div class="button-btn"> <button href="#" id="btn1" class="btn1">Click</button> <button href="#" id="btn2" class="btn2">Click</button> <button href="#" id="btn3" class="btn3">Click</button> </div> </div> </body>

要在单击时更改按钮的颜色,您可以使用 JavaScript 如下:

$( document ).ready(function() {
  $( ".js-click" ).click(function() {
    $( ".js-click" ).css('background', 'green');
  });
});

你的 CSS 可能是这样的:

button {
  background: none;
}

和你的 html 代码:

<button class="js-click">Click me!</button>

最好的方法是使用 JavaScript。 为单击按钮时添加事件侦听器,然后直接编辑样式或添加类。

话虽如此,使用 hacks 可以实现完整的 CSS 解决方案: codepen

 body { background-color: #7a86cb; margin: 20px; } #button1-clicked { display: none; } .button { position: relative; width: 120px; height: 45px; text-align: center; white-space: nowrap; line-height: 45px; border-radius: 30px; cursor: pointer; background-color: rgba(0, 0, 0, 0.1); border: 2px solid black; color: white; } .button:active { transform: translateY(4px); } .button:hover { background: #7a86cb; } .button::before { content: 'Click'; } .button .cover { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; cursor: pointer; } #button1-clicked:active ~ #button1 { transform: translateY(4px); } #button1-clicked:checked ~ #button1 { background: green; border-color: red; } #button1-clicked:checked ~ #button1::before { content: 'Clicked!' } /* Hide the label to make sure the user cannot "unclick" */ #button1-clicked:checked ~ #button1 .cover { display: none; }
 <input type="checkbox" id="button1-clicked"> <div class="button" id="button1" role="button"> <label for="button1-clicked" class="cover"></label> </div>

请避免在生产中使用这种东西,并使用 JavaScript 事件侦听器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM