如果在点击时图像发生变化,如何在javascript中添加淡入效果?

时间:2017-03-16 08:46:39

标签: javascript html css html5

当您为下一张图像点击下一张图像时,如果图像发生变化,如何添加淡入或淡出效果?我在这里使用画布。我没有使用自动幻灯片,也没有使用超时。基本上,它在图像转换期间增加了效果。

QueueUserAPC

==================================

function nextimg() {

i++;
if(i > 0 && i < 6) {
    image.src = 'images/' + i + '.jpg';
}

if(msg1 == i) {
    msg = "Fallout 4";
    document.getElementById("caption").innerHTML = msg;
}
else if(msg2 == i) {
    msg = "Diamond City";
    document.getElementById("caption").innerHTML = msg;
}
else if(msg3 == i) {
    msg = "Commonwealth";
    document.getElementById("caption").innerHTML = msg;
}
else if(msg4 == i) {
    msg = "Glowing Sea";
    document.getElementById("caption").innerHTML = msg;
}
else if(msg5 == i) {
    msg = "Cambridge";
    document.getElementById("caption").innerHTML = msg;
}

var canvas = document.getElementById("img_1").className += "fadeOutEffect";

var canvas = document.getElementById("img_1");
var context = canvas.getContext("2d");
    context.drawImage(image, 0,0, 500, 400);
}

=================================

#prevpic {
    opacity:1;
    transition: opacity 1s; 
}

#nextpic.fadeOutEffect {
    opacity:0;
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

function nextimg() {
    i++;
    if(i > 0 && i < 6) {
        image.src = 'images/' + i + '.jpg';
    }

    if(msg1 == i) {
        msg = "Fallout 4";
        document.getElementById("caption").innerHTML = msg;
    }
    else if(msg2 == i) {
        msg = "Diamond City";
        document.getElementById("caption").innerHTML = msg;
    }
    else if(msg3 == i) {
        msg = "Commonwealth";
        document.getElementById("caption").innerHTML = msg;
    }
    else if(msg4 == i) {
        msg = "Glowing Sea";
        document.getElementById("caption").innerHTML = msg;
    }
    else if(msg5 == i) {
        msg = "Cambridge";
        document.getElementById("caption").innerHTML = msg;
    }

    var canvas = document.getElementById("img_1");
    canvas.className += " fadeOutEffect"; // Add an space so do not concats existent classes
    canvas.addEventListener("transitionend", function transitionend() {
        canvas.removeEventListener("transitionend", transitionend, false);
        clearTimeout(tim);
        canvas.className = canvas.className.replace(" fadeOutEffect", "");
    }, false);
    var tim = setTimeout(transitionend, 1100); // To overcome old browsers
    var context = canvas.getContext("2d");
    context.drawImage(image, 0,0, 500, 400);
}

什么是监听transitionend事件并在事件结束时删除该类。画布将转换回opacity: 1。它也会超时,因此可以使浏览器仍然不支持transitionend事件。顺便说一下,他们现在几乎没用过旧浏览器(IE9等):http://caniuse.com/#search=transitionend你可以根据需要删除它。

Protip:保持你的缩进清洁。

Protip 2:要向元素添加文字,请使用textContent代替innerHTML。更快,允许没有任何预转换的特殊字符,例如普通<>