简体   繁体   中英

jQuery is not resizing images or playing them in a slideshow

So I have this jquery:

$(function () {
    //make the div take up the space given
    $('div#slideshow').width(100%);
    //make each slide fit within that div easily
    //I would prefer this be done by running through the slideshows div children,
    //rather than having to give each image the class of "slide", but I've had even worse luck with that
    $('.slide').each(function(index){
                $(this).width(90%);
        })
    //hide the first image
    $('#slideshow img:gt(0)').hide();
    setInterval(function () {
        //put each slide up for six seconds and cause it to fade out while the
        //new one fades in over a period of two seconds
        $('#slideshow :first-child').fadeTo(2000, 0)
            .next('img').fadeTo(2000, 1).end().appendTo('#slideshow');
    }, 6000);
});

with this HTML:

<div id="slideshow">
    <img style='position:relative;' width="400px" src="https://consumermediallc.files.wordpress.com/2014/11/totinos-stock-08-2014.jpg" alt="" class="slide" />
    <img src="https://36.media.tumblr.com/66fa7962b68e90da541078fcc9efdc25/tumblr_inline_nnby3oQs8s1si7eaa_500.jpg" alt="Lightning Ghost" class="slide" />
    <img src="http://ak-hdl.buzzfed.com/static/2014-05/enhanced/webdr02/14/7/enhanced-3829-1400068353-2.jpg" alt="Girraffe-dog" class="slide" />
    <img src="https://www.colourbox.com/preview/2291250-terrible-grimace-men-with-shovel.jpg" alt="Purpleish Kitty" class="slide" />
</div><!--slideshow-->

I'd say my comments in my jquery describe the trouble I'm having pretty well, when my code was just this:

$(function () {
        //hide the first image
        $('#slideshow img:gt(0)').hide();
        setInterval(function () {
            //put each slide up for six seconds and cause it to fade out while the
            //new one fades in over a period of two seconds
            $('#slideshow :first-child').fadeTo(2000, 0)
                .next('img').fadeTo(2000, 1).end().appendTo('#slideshow');
        }, 6000);
    });

It worked fine, but I also had to set up the div and the images it contained specifically for that code, the goal here is to make this code for a slideshow a bit more flexible. By the way, here's the JSFiddle I've been trying to get this to work on: http://jsfiddle.net/75wczrw7/

You have syntax error – wrap width percents in brackets like this in both width calls:

$('div#slideshow').width('100%');
...
$(this).width('90%');

Right now in your code the images keep on taking up new space unless all of them have loaded at least once. One more change you may need to make here is to give #slideshow a position : relative and .slide position:absolute.

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