簡體   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