Random background image with corresponding attribu

2020-04-16 06:50发布

问题:

I have a page that displays a random background image from an array of 5 images. I want to also have the appropriate attribution link for that image on the bottom of the page, but I'm not sure how to do this with javascript or php. This is what I have now:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript" ></script>

<script type="text/javascript">
 var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg'];
 $('body').css({'background-image': 'url(/sites/default/files/images/' + images[Math.floor(Math.random() * images.length)] + ')'});
</script>

this loads the background image just fine, but is there a way to add a link element to each image in the array and display the link somewhere on the page?

回答1:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- javascript/jQuery -->
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>

<a id ="link" href="#"></a>

<script type="text/javascript">
    var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg'];
    var links = ['home.html', 'contact.html', 'about.html', 'product.html', 'gallery.html'];
    var text = ['home', 'contact', 'about', 'product', 'gallery'];
    var rand = Math.floor(Math.random() * images.length);

    $('body').css({'background-image': 'url(/sites/default/files/images/' + images[rand] + ')'});
    $('#link').attr('href', links[rand]);
    $('#link').html(text[rand]);
</script>

</body>
</html>