html 刷新更新背景图


需求:每次刷新页面,随机获取背景图

实现方式:

1 通过js动态生成标签

<body>
    <script type="text/javascript">
	var bodyBgs = [];
	bodyBgs[0] = "/cas/img/login/bg/load1.jpg";
	bodyBgs[1] = "/cas/img/login/bg/load2.jpg";
	var randomBgIndex = Math.round( Math.random() * 1 );
	document.write('<div class="col-left" style="background: url(' + bodyBgs[randomBgIndex] + ') no-repeat"></div>');
    </script>
</body>

  缺点:虽然可以满足功能要求,但是在body中插入js,无论从代码简洁性还是用户体验都不太好;

2 jquery替换参数

根据标签的不同,有两种方式可以实现功能:

  • div标签,通过css定义背景图参数

  页面标签:

  <div id="imgload" class="col-left"></div>  

  jquery实现:

  $().ready(function(){
      var myPix = new Array("/cas/img/login/bg/load1.jpg","/cas/img/login/bg/load2.jpg");
      var randomNum=Math.floor(Math.random()*myPix.length);
      $("#imgload").css('background', 'url('+myPix[randomNum]+') no-repeat');
  };

 

  • 通过attr(),替换src参数

  页面标签:

  <img id="imgload">

  jquery实现:

  $().ready(function() {
      ar myPix = new Array("/cas/img/login/bg/load1.jpg","/cas/img/login/bg/load2.jpg");
      var randomNum=Math.floor(Math.random()*myPix.length);
      $("#imgload").attr('src', myPix[randomNum]);
  });

jquery参数替换方式较好一些,js代码可以整体维护,页面也比较简洁;







免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM