简体   繁体   English

如何在javascript滑块中淡入淡出?

[英]How to make fade in javascript slider?

I created a slider using javascript code and I want to add some motion effects in it like fade. 我使用javascript代码创建了一个滑块,我想在其中添加一些动画效果,如淡入淡出。

Here is my code: 这是我的代码:

 <script type="text/javascript">
        <!--
        var image1=new Image()
        image1.src="1.jpg"

        var image2=new Image()
        image2.src="2.jpg"

        var image3=new Image()
        image3.src="3.jpg"

        var image4=new Image()
        image4.src="4.jpg"
        //-->
    </script>

<script>
    <!--
    var step=1
    function slideit()
    {
        document.images.slide.src=eval("image"+step+".src")
        if(step<4)
        step++
        else
        step=1
        setTimeout("slideit() ",3500)
    }
    slideit()
    //-->
    </script>

Is there any code for the fade or other motions? 是否有任何淡入淡出或其他动作的代码?

Any help would be appreciated. 任何帮助,将不胜感激。

Thanks in Advance. 提前致谢。

Yes, there are entire jquery plugins developed for just these types of things. 是的,有完整的jquery插件只为这些类型的东西开发。 easySlider is one, flexSlider is another. easySlider是其中之一,flexSlider是另一个。 Bootstrap has a slider they call carousel, which while only comes with sliding effects, it's fairly easy to add cross fading. Bootstrap有一个滑块,它们称为carousel,虽然只有滑动效果,但添加交叉渐变相当容易。

Looking at the code, there are few things that must absolutely change: 看一下代码,很少有东西必须绝对改变:

  • Many similar elements must be put into an array rather than in many similar-named variables. 许多类似的元素必须放在一个数组中,而不是放在许多类似命名的变量中。

  • Do not use eval , in fact, KILL IT WITH FIRE so it won't get back. 事实上,不要使用eval ,因为它不会回来。 eval is a keyword that is abused to compensate a lack of competence. eval是一个被滥用来补偿缺乏能力的关键词。

Then, for fading and motions, you may take a look at these sliders and customize one of them with jQuery if needed. 然后,对于淡入淡出和动作,您可以查看这些滑块并根据需要使用jQuery自定义其中一个。 Ideally, you should not have to deal with image elements yourself as it's the slider's job. 理想情况下,您不必自己处理图像元素,因为它是滑块的工作。

Give the slides container an id ig "images", then you can create img dom element and append it to the container, then change it's source every 3.5 sec and use jquery to animate the opacity(fadeIn). 给幻灯片容器一个id“图像”,然后你可以创建img dom元素并将其附加到容器,然后每3.5秒更改一次源,并使用jquery为不透明度设置动画(fadeIn)。

$(document).ready(function () {
    var src = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];
    var slide = 0;
    var img = new Image();
    document.getElementById('images').appendChild(img);

    function slideit() {
        img.style.opacity = 0;
        img.src = src[slide % 4]; //%4 will reset the counter to 0 after 3.
        img.onload = function () {
            $('#images img').animate({
                'opacity': 1
            }, 500);
            slide++;
        };
        setTimeout(slideit, 3500);
    }
    slideit();
});

jsfiddle 的jsfiddle

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

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