首页 > 解决方案 > 按下按钮时如何启动图像渐变?

问题描述

我的渐变代码有问题,我用css编码,一切都很完美,但问题是图像的渐变是自动启动的,所以我想在按下按钮时启动渐变

我试图将它与 java 脚本中的函数连接,但它不起作用

<style>
.image {
width: 50vw;
height: 70vh;
position relative;
margin-top: -49%;
background: linear-gradient(-135deg, #ffffff, #ffffff, #ffffff, #ffffff, 
#d9d9d9, #b3b3b3, #8c8c8c, #595959, #333333, #000000 ,#000000 ,#000000);
background-size: 400% 400%;
-webkit-animation: Gradient 5s ;
-moz-animation: Gradient 5s ;
animation: Gradient 5s ;
animation-fill-mode: forwards;
}

@keyframes Gradient {
0% {
    background-position: 0% 50%
}
100% {
    background-position: 100% 50%
}
}
</style>
<body>

<input type="radio" name="switch" value="on" onclick="changeImage()" />
<input type="radio" name="switch" value="off" checked="checked"         
onclick="changeImage()"/>

</div>


<div class = "image">
<img src="image/bef_logo.png" id="myImage" style= "width: 10vw; position: 
absolute; margin: 11% 0% 0% 19%;">
</div>

<script>
    function changeImage() {
        var image = document.getElementById('myImage');
        if (image.src.match("image/bef_logo.png")) {
            image.src = "image/aft_logo.png";
        }
        else {
            image.src = "image/bef_logo.png";
        }
    }
</script>

</body>

这是我的代码,图像和渐变..我想要的只是在应用函数changeimage()时开始渐变(出现在css代码.image中)

标签: javascripthtmlcsscss-animationsgradient

解决方案


您可以通过在 CSS 中创建一个新类来使动画独立于图像:

.switch-animation{
 -webkit-animation: Gradient 5s ;
-moz-animation: Gradient 5s ;
animation: Gradient 5s ;
animation-fill-mode: forwards;
}

所有与动画相关的内容都被取出并添加到该类中。

一旦你有了这个类,在你的changeImage()函数的某个地方添加下面的代码行,这将切换动画。

<script>
   function changeImage() {

    if (image.src.match("image/bef_logo.png")) {

        //Code to toggle animating class:
        document.querySelector('.image').classList.toggle('switch-animation');

        image.src = "image/aft_logo.png";

    }
    else {
        image.src = "image/bef_logo.png";
    }

   }
</script>

推荐阅读