我是第一次使用removeChild方法。我使用javascript修改了导航栏,使其更改为固定位置并与用户一起滚动。发生这种情况时,这会使body div的内容略有上升。结果,当导航栏的位置更改时,我设法插入了一个红色框(以后将为白色)以占用额外的空间。
当用户滚动到顶部时,我需要删除该红色框,但似乎无法启动remove child函数。如果有人可以看一下并指出正确的方向,那将会很不错!
代码(相关代码部分以粗体显示):
var fillerState = false;
// fixed positioning on scroll property for taskbar:
window.addEventListener('scroll', function (evt) {
var distance_from_top = document.body.scrollTop;
if (distance_from_top <= 80) {
document.getElementById("navBar").style.position = "static";
document.getElementById("navBarList").style.borderBottom = "solid black 4px";
document.getElementById("navBar").style.borderTop = "initial";
var myCollection = document.getElementsByClassName("navBarLink");
var collectionLength = myCollection.length;
for(var i = 0; i < collectionLength; i++){
myCollection[i].style.borderTopLeftRadius = "1em";
myCollection[i].style.borderTopRightRadius = "1em";
myCollection[i].style.borderBottomLeftRadius = "initial";
myCollection[i].style.borderBottomRightRadius = "initial";
}
// stops loads of boxes from forming:
**if(fillerState == true){
var parentRemove = document.getElementById("bodyDiv");
var fillerBoxRemove = document.getElementById("fillerBox");
parentRemove.removeChild(fillerBoxRemove);
fillerState = false;
alert(fillerState);**
}
}
else if(distance_from_top > 80) {
document.getElementById("navBar").style.position = "fixed";
document.getElementById("navBar").style.top = "0px";
document.getElementById("navBar").style.borderTop = "solid black 4px";
document.getElementById("navBarList").style.borderBottom = "initial";
var myCollection = document.getElementsByClassName("navBarLink");
var collectionLength = myCollection.length;
if(fillerState == false){
// sets filler element so that the page doesn't bounce:
var filler = document.createElement("div");
filler.style.width = "200px";
filler.style.height = "80px";
filler.style.backgroundColor = "red";
filler.style.id = "fillerBox";
//defines where the new element will be placed:
var parent = document.getElementById("bodyDiv");
var brother = document.getElementById("leftColumn");
parent.insertBefore(filler,brother);
fillerState = true;
}
for(var i = 0; i < collectionLength; i++){
myCollection[i].style.borderTopLeftRadius = "initial";
myCollection[i].style.borderTopRightRadius = "initial";
myCollection[i].style.borderBottomLeftRadius = "1em";
myCollection[i].style.borderBottomRightRadius = "1em";
}
}
});
最佳答案
正如斜眼指出的那样,在制作元素时,您将其设置为style.id,这是不对的。
更改:
filler.style.id = "fillerBox";
至:
filler.id = "fillerBox";
并且您的代码将起作用。
或者,您可以按照他人的建议进行操作,并在html本身中创建框,将其设置为没有显示的类,然后更改其类。不仅容易,而且阻止您创建和销毁。这样可以减少资源密集型。
关于javascript - removeChild语法-我需要一双经验丰富的眼睛,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36093479/