頁面上有白色文本,其下方有一個按鈕。此外,也套用動畫漸層來填滿文字。單擊該按鈕時,-webkit-text-fill-color 屬性將變為透明,從而導致文字顏色突然變化以匹配漸變。
-webkit-text-fill-color
透明
如下:https://codepen.io/hvyjhqnt-the-vuer/pen/poQdaLQ
能否實現從白色到漸變的平滑過渡? (-webkit-text-fill-color 屬性不直接支援transition)
transition
CSS 顏色屬性是可轉換的,因此請使用它。
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Smooth color change in js</title> <link rel="stylesheet" href="css/styles.css" /> <style> @font-face { font-family: Alice; src: local(Alice), url(../fonts/Alice-Regular.ttf); } html { height: 100%; } body { text-align: center; justify-content: center; align-items: center; background-color: #201e1e; } h1 { font-family: Alice; font-size: 7vw; background: linear-gradient(45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); -webkit-background-clip: text; background-clip: text; color: white; transition: color 5s linear; background-size: 500% 500%; animation: textShine 5s ease-in-out infinite alternate; } button { font-family: Alice; font-size: 20px; padding: 10px 20px; background-color: #201e1e; color: white; border: 2px solid white; cursor: pointer; transition: background-color 0.3s ease; } button:hover { background: linear-gradient(45deg, #38292c, #362d31, #363c3d, #2f3026); } @keyframes textShine { 0% { background-position: 0% 50%; } 100% { background-position: 100% 50%; } } </style> </head> <body> <h1 id="my-text" class="show">Hello word</h1> <button id="button" onclick="changeColor()">Переливайся</button> <script src="script.js"></script> </body> <script> let col; function changeColor() { const myText = document.getElementById("my-text"); const computedStyle = window.getComputedStyle(myText); const textColor = computedStyle.getPropertyValue("color"); if (textColor === "rgb(255, 255, 255)") { col = "transparent"; document.getElementById("button").innerHTML = "Не переливайся"; } else { col = "white"; document.getElementById("button").innerHTML = "Переливайся"; } myText.style.color = col; } </script>
CSS 顏色屬性是可轉換的,因此請使用它。