Vanilla javascript, not CSS or jQuery, fade in, fade out image change

时光总嘲笑我的痴心妄想 提交于 2019-12-11 02:56:43

问题


I know this is fairly easy in jQuery, but I want to do this in plain 'ol "will be around forever" javascript.

I have a dropdown select on my page. I choose one of 8 options. There is a default image showing on the page. When I select an option, the image changes to that pic. It all works fine.

But I want to make the image change a fade out, fade in switch over because I, like most of you, can't leave well alone. We have to keep fiddling.

The javascript that I have, which is triggered by an onchange="setPicture()" on the select dropdown is:

function setPicture(){
    var img = document.getElementById("mySelectTag");
    var value = img.options[img.selectedIndex].value;
    document.getElementById("myImageDiv").src = value;
}

This works fine. The value of the selected index is a string with the path for each image. I just want a fade out then fade in stuck in there somewhere. I have fiddled about a bit, calling another function before changing the src but no luck.

Can someone point me in the right direction?


回答1:


The easier way would be to use css keyframes alone.

But from javascript there is the web animation api made for that.

Here is a quick modif from the example, to match your case.

function setPicture(){
 alice.animate(
  [
    { opacity: 1 },
    { opacity: .1},
    { opacity: 1 }
  ], {
    duration: 3000,
    iterations: Infinity
  }
 )
}
<button onclick="setPicture()">
  OPACITY ANIMATION
   </button>

<img id="alice" 
     src="https://mdn.mozillademos.org/files/13843/tumbling-alice_optimized.gif"
     >
  </img>



回答2:


How about setting the image default CSS with the opacity of 0 and with transition time then in JavaScript just add a class that will make the opacity set to 1

HTML: 
    <img class="img1" src="sampleimg.jpg">

CSS: 
    .img1 {
        opacity: 0;
        transition: all .3s;
    }
    .img1.show {
        opacity: 1;
    }

JS:
    function setPicture() {
        var img = document.querySelector('.img1');
        img.src = 'urlofnewimage';
        img.classList.add('show');
    }

Hope this helps.




回答3:


Juste one function for all :

function fadeOutEffect(target) {
    var fadeTarget = document.getElementById(target);
    fadeTarget.style.opacity = 1;
    fadeTarget.style.transition = "opacity 2s";
    fadeTarget.style.opacity = 0;
    setTimeout(function(){
        fadeTarget.style.display = "none";
    }, 2000);;
}


来源:https://stackoverflow.com/questions/53784910/vanilla-javascript-not-css-or-jquery-fade-in-fade-out-image-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!