
1 nikejaycn 2011-04-12 23:07:44 +08:00 document.images.bg.src="+ imgs[currIndex] +"; 怎么看我都觉得这句代码有问题。"+ imgs[currIndex] +"? |
2 iugo OP @nikejaycn 呃,请问,那该怎么写呢? document.write(imgs[currIndex]) 中直接写 imgs[currIndex] 可以看到随机选择的图片的 url ,但是写成 document.images.bg.src="imgs[currIndex]"; 无效。 document.body.style.bakgroundImage="url("+imgs[currIndex]+")" 中, imgs[currIndex] 两边是加了 “+” 的,所以我加上了,但依旧无效。呃,我不知道标准的该怎么写。。。 |
3 kayue 2011-04-12 23:20:45 +08:00 var currIndex = Math.floor( Math.random() * n); |
4 kayue 2011-04-12 23:23:12 +08:00 document.images.bg.src = imgs[currIndex]; |
5 nikejaycn 2011-04-12 23:25:55 +08:00 var n=imgs.length - 1; |
6 kayue 2011-04-12 23:26:19 +08:00 currIndex 会出现 0...3 的原因是 Math.round() 例如当 Math.random() = 2.7 的时候,round 后就成了 3 用 Math.floor 代替即可。 |
8 kayue 2011-04-12 23:30:08 +08:00 Math.round() * 3 的最大值是 2.999 用 Math.floor(向下取其整数)的话即使 2.999 也只会传回 2。 正解也。 |
9 iugo OP @kayue 谢谢。 我学习到了两点。 一:Math.round 与 Math.round 。返回小于等于数字参数的最大整数,对数字进行下舍入。返回数字最接近的整数,四舍五入 。( http://www.dreamdu.com/Javascript/Math.round/ )虽然还是不甚明了,但起码有个大概的印象,将来深入的时候会容易些。 二:引号内的一般都是 确定值 (我不知道该怎么表达)而不是变量,对变量,不要加引号。 |
10 kayue 2011-04-12 23:32:43 +08:00 而楼主的 document.images.bg.src="+ imgs[currIndex] +"; 这句跟本就有 syntax 错误。 element.src = "somewhere"; 是相等于 var theSrc = "somewhere"; element.src = theSrc; |
12 darasion 2011-04-12 23:36:20 +08:00 document.images.bg.src 是哪来的?? |
13 chone 2011-04-12 23:49:16 +08:00 http://jsfiddle.net/uUWuc/ var imgs = [ 'http://www.google.com/logos/2011/firstmaninspace11-hp.jpg', 'http://l.yimg.com/a/i/ww/met/logo/20100909/yahoo_logo_fr.png', 'http://images.apple.com/euro/home/images/ipad2_hero2_20110302.png' ]; var n = imgs.length; var currIndex = Math.floor(Math.random()*n); var bgEl = document.getElementById('bg'); bgEl.src = imgs[currIndex]; |