簡體   English   中英

div元素在單擊時將淡入(或過渡)頁面的背景色

[英]div element, when clicked, will fade (or transition) the page's background color

令我驚訝的是,經過大量搜索后,我找不到答案。 我正在使用簡單的Javascript來幫助您了解我要完成的任務,但是如果可以使用CSS做到這一點,我也很樂意嘗試一下。 另外,請記住,我需要這種顏色而不是圖像。

<head>
<link rel="stylesheet" type="text/css" href="bground.css">
</head>

<body>

<div id='a' class="circle" onclick="myFunction()"> <br> <br> Click me for blue. </div>
<br>

<script>
function myFunction() {
    document.body.style.backgroundColor="blue";}
</script>

</body>

本質上,我希望單擊按鈕來緩慢地改變背景,就像淡入淡出或過渡效果一樣,但是過去兩天我遇到了很多困難。

您可以為此使用CSS過渡。

 function myFunction() { document.body.className="B"; } 
 body { background: red; } body.B { background: blue; transition: background 4s; } 
 <body class=A> <div id='a' class="circle" onclick="myFunction()"> <br> <br> Click me for blue. </div> <br> </body> 

請注意,我使用了一個類。 在javascript中混合樣式元素(例如顏色)被認為是不好的做法。

這是使用復選框黑客的純CSS解決方案。

柱塞

CSS:

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}
label { 
  -webkit-appearance: push-button;
  -moz-appearance: button; 
  display: inline-block;
  margin: 60px 0 10px 0;
  cursor: pointer;
}

/* Default State */
div {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
}
input[type=checkbox] ~div {
   -webkit-transition: all 2s ease-in-out;
   -o-transition: all 2s ease-in-out;
   -moz-transition: all 2s ease-in-out;
   transition: all 2s ease-in-out;
}
/* Toggled State */

input[type=checkbox]:checked ~ div {
   background: red;
   -webkit-transition: all 2s ease-in-out;
   -o-transition: all 2s ease-in-out;
   -moz-transition: all 2s ease-in-out;
   transition: all 2s ease-in-out;
}

HTML:

<label for="toggle-1">I'm a toggle</label>
<input type="checkbox" id="toggle-1">
<div>I'm controlled by toggle. No JavaScript!</div>

我修改了這篇文章中Andy的回答,基本上只是在其中添加了CSS動畫: 我可以在CSS中產生onclick效果嗎?

本質上,您所要做的就是使用復選框作為切換以觸發類更改。

<!DOCTYPE html>
<html lang="en-GB>
<head>
  <script>
    document.getElementById( 'btn' ).onclick = function() {
      document.body.style.background = 'pink';
    }
  </script>

  <style>
    body {
      background: red;
      transition: background 1s;
    }
  </style>
</head>
<body>
  <div id="btn">Click Me!</div>
</body>
</html>

JSFiddle上測試

注意 :嗯。花了我一段時間,因為我認為它不起作用,只是我放了2000s而不是2000ms 我知道現在可能還有其他答案:(

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM