使用Javascript图像shuffle更改标头标记和链接

时间:2013-11-06 18:13:05

标签: javascript jquery html

我使用以下脚本在刷新时更改背景照片:

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

我需要更改相关说明并与每张照片相关联。以下是需要更改的标记:

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

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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开头。

答案 2 :(得分: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);

}

Here test in jsFiddle

相关问题