简体   繁体   中英

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.

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. easySlider is one, flexSlider is another. Bootstrap has a slider they call carousel, which while only comes with sliding effects, it's fairly easy to add cross fading.

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 is a keyword that is abused to compensate a lack of competence.

Then, for fading and motions, you may take a look at these sliders and customize one of them with jQuery if needed. 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).

$(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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