吴思奇的个人博客(⁄ ⁄•⁄ω⁄•⁄ ⁄)~

10月 27

用JavaScript实现随机提取指定的图片作为网页背景

其实这个功能几个月前都实现了,但是写法有些问题,打算修改下,换个写法。

思路

提取网站下的images里的background文件夹里6张图里的随机取一张图,作为网页背景。
js直接放在了header.php尾部。

用在自己网站的代码

<script>

bg_img= ['<?php $this->options->themeUrl('images/background/1.jpg'); ?>',
         '<?php $this->options->themeUrl('images/background/2.jpg'); ?>',
         '<?php $this->options->themeUrl('images/background/3.jpg'); ?>',
         '<?php $this->options->themeUrl('images/background/4.jpg'); ?>',
         '<?php $this->options->themeUrl('images/background/5.jpg'); ?>',
         '<?php $this->options->themeUrl('images/background/6.jpg'); ?>'];  //调用图片路径(我网站模板是用的themeUrl函数获取当前模板路径,根据实际情况决定怎么写)

document.getElementsByTagName("body")[0].style.background = "url("+bg_img[Math.floor(Math.random()*(bg_img.length))]+")";//随机背景图
document.getElementsByTagName("body")[0].style.backgroundPosition = "center";
document.getElementsByTagName("body")[0].style.backgroundRepeat = "no-repeat";
document.getElementsByTagName("body")[0].style.backgroundAttachment = "fixed";

</script>

不用php也可以这样写

<script>

bg_img = ["http://xxxx/1.jpg", 
          "http://xxx/2.jpg", 
          "http://xxx/3.jpg", 
          "http://xxx/4.jpg", 
          "http://xxx/5.jpg", 
          "http://xxx/6.jpg"]; //调用图片地址/路径(改为自己的)

document.getElementsByTagName("body")[0].style.background = "url("+bg_img[Math.floor(Math.random()*(bg_img.length))]+")";//随机背景图
document.getElementsByTagName("body")[0].style.backgroundPosition = "center";
document.getElementsByTagName("body")[0].style.backgroundRepeat = "no-repeat";
document.getElementsByTagName("body")[0].style.backgroundAttachment = "fixed";

</script>

写的时候遇到的问题

开始错用了document.body ,发现这个除了IE,其他浏览器都不认。
改为了document.getElementsByTagName。
开始为了图方便 把JS文件放到头部了。导致执行这个js的时候,body还没有出现的情况,一般js要放在html末尾(后)

关于getElementsByTagName()

getElementsByTagName() 方法可返回带有指定标签名的对象的集合。

语法

document.getElementsByTagName(tagname)

返回值

类型:NodeList 对象,描述:指定标签名的元素集合

浏览器支持

所有主要浏览器都支持 getElementsByTagName() 方法


转载请注明出处(https://www.wusiqi.cn/archives/455/)
来源网站:547的Blog - 萌萌哒 ~

标签:JavaScript, js

已有 2 人抢先你了

  1. wintsa

    问一下为什么背景把评论遮住了,你这个不会。

  2. 不觉得写麻烦了么

添加新评论

关于我

90后/留学党/不可爱的蓝孩子
欢迎来新浪微博找我玩
Email:admin@wusiqi.cn

最新文章

最近回复

  • Ether:感谢,今天手贱又更新了系统,之前1903的改过的BIOS微码又寄...
  • X99:谢谢 解决了我的问题
  • WuSiqi:感谢提醒,已经修复啦。最近工作太忙,都没怎么看这个破站。哈哈哈哈
  • 丘先森:好用,记录一下。你好你网址的SSL过期了。
  • WuSiqi:微信:2.8.0.112到最新版本都支持 QQ:9.2.3.26...
  • chen:博主,请问下这个补丁对QQ和微信的版本有限制吗?
  • teidl:怎么会有高增益 高增益不是有单独的放大电路么
  • ete:到了各种事情导致心情很不好
  • nzeo:谢谢!解决了我的问题
  • 奶牛君:日版A845亲测有效 感谢分享
  • 友情链接

    其它