-2

I use the following script to change a background photo upon refresh:

<script type="text/javascript">
var randomImage = Math.floor((Math.random()*4)+1);
var homePage = document.getElementById('homepage');

homePage.style.backgroundImage= 'url("http://sample.com/images/bg/'+randomImage+'.jpg")';
</script>

I need to change the associated description and link with each photo. Here is the tag that needs to change:

<h3><a href="images/photographs/sample/sample.html">Description</a></h3>

Thank you for the help.

4

3 回答 3

0

这里有一个想法供你参考:

HTML:

<ul id="description">
  <li><a href="images/photographs/sample/stuff.html">description for img #1</a></li>
  <li><a href="images/photographs/sample/sample.html">description for img #2</a></li>
  <li><a href="images/photographs/sample/dude.html">description for img #3</a></li>
  <li><a href="images/photographs/sample/what.html">description for img #4</a></li>
</ul>

CSS:

#description li { display: none; }

JS:

var randomSeed = Math.floor((Math.random()*4)+1);
var description = document.getElementById("description");
var homePage = document.getElementById('homepage');
homePage.style.backgroundImage= 'url("http://sample.com/images/bg/'+randomSeed+'.jpg")';
description.getElementsByTagName('li')[randomSeed-1].style.display = "block";

我基本上把所有的东西都隐藏起来,只显示相关的描述。

-1 是因为数组索引从 0 开始。

于 2013-11-06T18:35:56.797 回答
0

这是我的解决方案,使用 jQuery

    $(document).ready(function(){
        clickLink();
    });

    function clickLink(){
        $(document).on('click', '#link-image', function(e){
            e.preventDefault();
            var bgs = ["http://lorempixel.com/200/200/sports/1/", "http://lorempixel.com/200/200/sports/2/", "http://lorempixel.com/200/200/sports/3/", "http://lorempixel.com/200/200/sports/4/" ]
            var num = getRandomArbitrary();
            console.log(num);
            $('#homepage').css({"background":'url('+bgs[num]+')', border : "1px solid"});
            $(this).attr("href" , bgs[num]).text("Description Image " + num);
        });
    }

    function getRandomArbitrary() {
      return parseInt(Math.random() * 4);

}

这里在 jsFiddle 中测试

于 2013-11-06T18:57:22.020 回答
0

最好使用 jQuery 操作 css 属性。更容易维护。

于 2013-11-06T18:23:25.787 回答