Javascript or JQuery for background image slidesho

2019-08-20 10:11发布

问题:

I want to create a slideshow using the background image of a div. I don´t want the images to rotate automatically, instead I want to use standard prev and next buttons to change the div´s background image. In total there will be around 6 images to scroll through. It needs to be a background image as the div has some other content in it.

Think this can be achieved using JQuery but not sure how.

I have the following code which automatically rotates through the images, but I don´t want them to change automatically. I need to be able to scroll through the images using the next and prev buttons.

var bgArr = ["images/img-restaurante-2.jpg", "images/img-restaurante-3.jpg", "images/img-restaurante-4.jpg", "images/img-restaurante-5.jpg", "images/img-restaurante-1.jpg"];
var i = 0;

// Start the slide show
var interval = self.setInterval("swapBkgnd()", 20000);

function swapBkgnd() {
    if (i > (bgArr.length - 1)) {
        i = 0
        $("#restaurante").css("background-image", "url(" + bgArr[i] + ")");
    } else {
        $("#restaurante").css("background-image", "url(" + bgArr[i] + ")");
    }
    i++;
};

Can anyone help me?

回答1:

<script type="text/javascript">

    var bgArr = ["images/img-restaurante-2.jpg", "images/img-restaurante-3.jpg", "images/img-restaurante-4.jpg", "images/img-restaurante-5.jpg", "images/img-restaurante-1.jpg" ]; 
    var i=0;

    // Start the slide show
    setInterval(function() {
        $("#restaurante").css("background-image", "url("+bgArr[i]+")");
        (i < bgArr.length-1) ? i++ : i=0 
    }, 20000); 

</script>


回答2:

Take a look at Gallerific (jQuery plugin) very slick.

Super simple to implement you just put your images in a Unordered List (UL) (in the example below the "thumbs-min" is the UL) and then do something like this;

    $(document).ready(function() {              
    // Initialize Minimal Galleriffic Gallery
    $('#gallery').galleriffic('#thumbs-min', {
    imageContainerSel:      '#slideshow',
    controlsContainerSel:   '#controls'
    });
});

Collection of jQuery slideshow related plugins here.Might be something more like Supsersized is what your looking for.



回答3:

You can use a plugin JCaroussel lite for example : http://www.gmarwaha.com/jquery/jcarousellite/



回答4:

var bgArr = ["images/img-restaurante-2.jpg", "images/img-restaurante-3.jpg", "images/img-restaurante-4.jpg", "images/img-restaurante-5.jpg", "images/img-restaurante-1.jpg" ]; 
var i=0;



function next()
{
  i = (i== bgArr.length-1 ? 0 : i++);
  $("#restaurante").css("background-image", "url("+bgArr[i]+")");
}
function prev()
{
  i = ( i==0 ? bgArr.length-1 : i--);
  $("#restaurante").css("background-image", "url("+bgArr[i]+")");
}


<a href="Prev" onclick="prev()">Prev</a>
<a href="Next" onclick="next()">Next</a>