这个脚本每秒钟都会使用AJAX打开一个页面,并将内容返回到这个页面上的一个新div中,这个div是它动态创建的。但不幸的是,它们是相互重叠的。我想在顶部创建每个新的div。我真的不想使用jquery或类似的东西。
对此的任何帮助都非常感激,我对JS不是很有信心,所以如果不是很明显,你能给我一个小小的解释吗?:)谢谢
function timedCount()
{
min = Math.floor(s/60);
sec = s-(min*60);
if(sec < 10) { sec = '0'+sec; }
if(min >= 60) { min = min-15; }
if(quit == 0) { document.getElementById('mTime').innerHTML = min+':'+sec; }
s=s+1;
var ajaxRequest;
try { ajaxRequest = new XMLHttpRequest(); } catch (e){
try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {
try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.responseText != '')
{
if(ajaxRequest.responseText == 'HT') {
document.getElementById('mTime').innerHTML = 'Half Time';
t=setTimeout("timedCount()",(3600-s)*1000);
quit=1;
return;
}
if(ajaxRequest.responseText == 'FT') {
document.getElementById('mTime').innerHTML = 'Full Time';
quit=1;
return;
}
el = document.createElement('rep'+i);
el.innerHTML = ajaxRequest.responseText +'<br>';
document.getElementById('container').appendChild(el);
i=i+1;
}
}
ajaxRequest.open("GET", "getMatch.php", true);
ajaxRequest.send(null);
}
您试过使用insertBefore
吗?
你可以改变行:
document.getElementById('container').appendChild(el);
var container = document.getElementById('container');
container.insertBefore(el, container.firstChild);
container.firstChild
将为您提供对容器内第一个元素的引用,并将el
放在其前面。
您需要insertBefore函数
var parent = document.getElementById('container');
parent.insertBefore(el, parent.firstChild);
注意,如果parent为空,则parent。因此,firstChild为null,然后el将插入到parent的末尾,这是您想要的。
appendChild方法总是在集合的末尾添加新节点,这就是为什么它出现在底部-参见http://msdn.microsoft.com/en-us/library/ms535934(v=VS.85).aspx
使用这里记录的insertBefore方法:http://msdn.microsoft.com/en-us/library/ms535934(v=VS.85).aspx。你可以使用document.getElementById('container')。firstChild作为第二个参数
通常,如果我真的想在所有其他元素上放置一个div,我会使用css position和z-index,比如:
div{
position: absolute;
z-index: 9999;
}
:)