Javascript淡出效果无法使图像消失

时间:2017-06-19 06:59:28

标签: javascript html css

我可以对图像进行淡出效果,但是效果之后,图像仍会显示在屏幕上。我希望在2s淡出效果后使其成为display: none;。怎么办呢?

document.getElementById("imgX").style.animation = "fadeout 2s";
@keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

         /* Firefox < 16 */
@-moz-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Internet Explorer */
@-ms-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Opera < 12.1 */
@-o-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}
<img id="imgX" src="x.png" />

2 个答案:

答案 0 :(得分:3)

添加forwards

document.getElementById("imgX").style.animation = "fadeout 2s forwards";

答案 1 :(得分:2)

forwards添加到动画声明

document.getElementById("imgX").style.animation = "fadeout 2s forwards";
@keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

         /* Firefox < 16 */
@-moz-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Internet Explorer */
@-ms-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}

/* Opera < 12.1 */
@-o-keyframes fadeout {
    from { opacity: 1; }
    to   { opacity: 0; }
}
<img id="imgX" src="x.png" />