简体   繁体   English

使用简单的JS更改滑块img不透明度

[英]Changing slider img opacity using simple JS

How i can add some fade effect by changingimg opacity using only simple JS(not Jquery)? 我如何仅使用简单的JS(而不是Jquery)通过更改img不透明度来添加一些淡入淡出效果?

var step = 12;
var total = 60;

function slide(x) {
    var image = document.getElementsByClassName("clickSliderimg");
    for (var i = 0; i < image.length; i++) {
        step = step + x;
        if (step > total) {
            step = 12;
        }
        if (step < 12) {
            step = total;
        }
        image[i].src = "css/images/img" + step + ".jpg";
    };
}

Simply reduce the opacity and put it in a loop that repeats itself until the picture has opacity 0, then set display to none: 只需降低不透明度,然后将其置于一个循环中,该循环会重复进行直到图片的不透明度为0,然后将display设置为none:

var img = document.getElementById('id of image to be faded').style;
  img.opacity = 1; 
(function fade(){(img.opacity-=.1)<0?img.display="none":setTimeout(fade,40)})();
[].forEach.call(document.getElementsByClassName("clickSliderimg"), function(el) {
   el.style.transition = 'opacity 4s';
   el.style.opacity = 0.5;
}

You should use CSS animations and transitions for simple animations and trigger them eg. 您应该为简单的动画使用CSS动画和过渡,并触发它们,例如。 by adding class to element. 通过向元素添加类。

Animating elements using JS tends to draw battery life, pollutes your code and is unmaintainable. 使用JS制作动画元素会延长电池寿命,污染代码,并且难以维护。

For performance reasons I would suggest you to use a mix of Javascript and CSS. 出于性能方面的考虑,我建议您同时使用Javascript和CSS。

So you can define some CSS classes such as: 因此,您可以定义一些CSS类,例如:

img {
    opacity: 0;
    transition: opacity .3s linear;
    -webkit-transition: opacity .3s linear;
    -moz-transition: opacity .3s linear;
    -ms-transition: opacity .3s linear;
    -o-transition: opacity .3s linear;
}

.visible {
    opacity: 1;
}

And then you can simply add / remove the "visible" class to your images. 然后,您可以简单地在图像中添加/删除“可见”类。

# Add class
image.className += " visible";

# Remove class
image.className.replace( /(?:^|\s)visible(?!\S)/g , '' )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM