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

时间:2019-10-03 13:48:03

标签: javascript html css header css-position

我想使用javascript在页面中插入标题。我不想从原始内容中隐藏任何内容,而只是在固定的上方添加标题。请记住,我不知道我要操纵的页面的内容。

我尝试在body元素上添加一个margin-top:

body{
  margin-top: 40px;
}

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

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

它们将保留在页面顶部。

您有什么建议吗?

2 个答案:

答案 0 :(得分:1)

尝试

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

答案 1 :(得分:0)

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

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; 
    }
}
}

现在,我不知道页面的结构,就可以在页面顶部插入一些东西。

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

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