2014-09-18 32 views
0

我有这段代码可以创建图片的幻灯片。唯一的问题是,它不能正确放置在网站上:图片的循环未正确放置在网站上

<html lang="en"> 
<head> 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<script type="text/javascript"> 

var pictureArchive= ['http://byggprojektoren.se/wp-content/uploads/2014/09/Shanghai.jpg','http://byggprojektoren.se/wp-content/uploads/2014/06/logo_739047_web.jpg','3.jpg','4.jpg']; 

window.onload=function() { 
var o=document.createElement('img'); 
o.setAttribute('id', 'image'); 
o.setAttribute('src', pictureArchive[0]); 
o.setAttribute('alt', ''); 
document.body.appendChild(o); 
rotate(pictureArchive.length); 
} 

function rotate(idx) { 
if(idx>=pictureArchive.length) { 
    idx=0; 
} 
document.getElementById('image').src=pictureArchive[idx++]; 
timerID=setTimeout('rotate('+idx+')', 3000); 
} 
</script> 
<style type="text/css"> 
</style> 
</head> 
<body> 
</body> 
</html> 

网址:Website

中的代码我在哪里写是错误的放置图片的地方是现在呢?

希望得到任何帮助。谢谢。

回答

0

您应该创建一个div来充当图像的“占位符”。现在你做一个document.body.appendChild(o) - 它只是将它附加到现有的主体内容。

只是这样做:<div id="placeholder"></div>并将此div放在您想要的页面中。 然后调用document.getElementById("placeholder").appendChild(o);,它会被放置在您的div

+0

事情是,我使用的Wordpress主题,它自动把它放在我想要它的位置。有没有什么办法可以将** document.body.appendChild(o)**拿走,然后自动将它正确放置?谢谢你或你的回复。 – RiMa 2014-09-18 17:34:54

+0

document.body.appendChild(o);将永远追加到你已经附加到身体的任何其他地方 - 如果你用document.body.appendChild()创建你的整个页面,你可以将它插入到正确的位置 - 或者你可以使用CSS来强制更好的位置 – 2014-09-18 17:36:10

+0

好的,谢谢你或这个帮助。我尝试过,但由于某种奇怪的原因,图像消失了。 – RiMa 2014-09-18 18:00:33

0

1)使封盖从你的员工保持全球知名度内:

(function(){ 
    window.onload = ... 
    function(){...} 
})(); 

2)不要使用“的window.onload =”,总是绑定事件监听器window.addEventListener(“load”,function(){})

3)使用“字符串写入函数是地狱之路,而timerID不是有用变量(它在函数结束时被emmidiatly终止)正常功能:

setTimeout (function(){rotate(idx);},3000); 

4),而IDX是正常范围的长住东西的地方它变种,这使得setTimeout和其他类似的东西太多easer执行

var idx = 0; 
function rotate(){ 
    if(idx...) idx = ...; 
    setTimeout(rotate,3000); 
} 

5)img.src不工作,始终做到这一点通过设定值属性image.setAttribute( “src” 用户,图像[IDX])

6)IDX ++的表达 - 编程的最糟糕的风格,时刻明确安全的地方算法的incremet

image.setAttribute(idx); //no idx++(!!!) this line must do SINGLE work - setAttribute!!! 
... 
idx++ // !at the end of function, explicitly make code clear! 
+0

对不起,但我是新来编程,所以我不真正了解你的更正。你能否将它们应用到我写的代码上,并只显示整个代码?谢谢。 – RiMa 2014-09-18 17:38:18