javascript - 按下按钮时如何启动图像渐变?
问题描述
我的渐变代码有问题,我用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中)
解决方案
您可以通过在 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>
推荐阅读
- java - 413 上传多部分文件时请求实体太大
- regex - 从 .yml 文件中 grep 特定值
- networking - 如何在 Ubuntu 中删除 SCTP 数据包中的“IPv4 地址参数”字段(可选)
- python - 使用 Adam 优化器在 FashionMNIST 上训练逻辑回归时出错
- sql - 填充桥表
- python - djnoer 给出 TypeError: permission_denied() got an unexpected keyword argument 'code' on get request on /users/me/
- laravel - 如何获取 id 以在控制器 laravel 中的另一个函数中使用
- python - 读取 pg_dump 文件发生在打开文件时
- r - R 中是否有代码可以根据其他标准区分同一列中的两个类别之间的差异?
- python - 创建一个程序,根据特定日期的温度计算分配给家庭供暖和制冷的天数