将页面的整个 html 内容向下移动?

Move whole html content of a page down?

我想在使用 javascript 的页面中插入 header。我不想隐藏原始内容中的任何内容,只是想在上面添加一个 header 是固定的。请记住,我不知道我要操作的页面的内容。

我尝试将 margin-top 添加到 body 元素:

body{
  margin-top: 40px;
}

但是如果有固定位置的元素:

.header{
   position: fixed;
   top: 0;
}

它们将保留在页面顶部。

你有什么建议吗?

尝试

body{
  padding-top: 40px;
}
header {
  position: fixed;
  top: 40px;
}

一种解决方案是遍历元素并找出位置固定的元素。

function moveDownFixedElements(){
let elems = document.body.getElementsByTagName("*");

for (let i = 0; i < elems.length ; i++) {
    if (window.getComputedStyle(elems[i], null).getPropertyValue('position') === 'fixed') {
        let style = window.getComputedStyle(elems[i]);
        let top = style.getPropertyValue('top');
        top = parseInt(top) + 40 + "px";
        elems[i].style.top = top; 
    }
}
}

现在我可以在不知道页面结构的情况下在其上插入内容。

编辑: 另一个非常简单的解决方案是使用转换 属性。

document.body.style.transform = "translateY(40px)";