移动父DIV而不影响子DIV

时间:2015-05-28 07:23:59

标签: javascript html css

我有DIV和其中的一些DIV,属性" position:absolute"。已知并修复了所有元素的大小和坐标。我必须移动父DIV,但是用户必须认为所有的儿童DIV都在视觉上留在原来的位置。

这似乎很容易,但是所有DIV内部的坐标也必须改变,并且完全由父DIV的移动距离(距离已知,例如20px)。

我试图更改父DIV的CSS并在循环中更改所有子元素的坐标,但它看起来并不好 - 我仍然可以看到子元素是如何移动的(移动是快,但不是看不见的。我希望通过一个简单的动作来移动父DIV,但所有DIV内部都自动改变了他们的位置,没有人能注意到这一点。我怎样才能做到这一点?表现很重要。

代码示例:

<div id="parent" style="position:absolute; top:50px; left:100px; width:500px; height:300px;">
    <div id="child1" style="position:absolute; top:10px; left:15px; width:20px; height:20px;"></div>
    <div id="child2" style="position:absolute; top:10px; left:55px; width:20px; height:20px;"></div>
</div>

2 个答案:

答案 0 :(得分:0)

你可以为任何任意项目(即,不知道它的起始位置,它有多少孩子或那些孩子的起始位置)你希望我使用CSS的translateX transform功能实现这一点 - 转移通过给定数量的像素向右移动父级,然后使用该数字的负数将子项向左移动,使其看起来是静态的。

我在下面提供了一些示例,前两个是由JavaScript事件触发的(为了简单起见,它们都是通过单击一个按钮触发的),第一个只是“跳过”并且第二个使用transition进行动画制作,第二个使用CSS中的鼠标操作触发,第一个在:hover上触发,第二个在:focus上。

Here's a Fiddle如果你想玩它。

更新: Here's another Fiddle,每次点击该按钮时,父母都会向左移动。

document.getElementById("button").addEventListener("click",function(event){
    var divs=document.querySelectorAll(".event"),x=divs.length;
    while(x--)
        divs[x].classList.toggle("shift");
    event.preventDefault();
},0);
/** PARENTS **/
.move{
    border:2px solid #000;
    height:70px;
    padding:40px 10px 10px;
    position:absolute;
    width:250px;
}
.move:first-of-type{left:20px;top:50px;}
.move:nth-of-type(2){left:30px;top:130px;}
.move:nth-of-type(3){left:40px;top:210px;}
.move:nth-of-type(4){left:50px;top:290px;}
/** CHILDREN **/
.move>div{
    background:#000;
    height:20px;
    position:absolute;
    top:10px;
    width:20px;
}
.move>div:first-child{left:15px;}
.move>div:nth-child(2){left:45px;}
.move>div:nth-child(3){left:75px;}
.move>div:nth-child(4){left:105px;}
/** ANIMATION **/
.animate,.animate>div{
    transition:transform .5s linear;
}
/** TRANSFORMATION **/
.shift,.hover:hover,.focus:focus{
    transform:translateX(100px);
}
.shift>div,.hover:hover>div,.focus:focus>div{
    transform:translateX(-100px);
}
/** MISC **/
button{
    top:10px;
    left:10px;
    position:relative;
}
*{box-sizing:border-box;line-height:20px;margin:0;outline:0;}
<button id="button">Click Me</button>
<div class="move event">
    <div></div>
    <p>I just jump across</p>
</div>
<div class="move event animate">
    <div></div>
    <div></div>
    <p>I transition across</p>
</div>
<div class="move hover animate">
    <div></div>
    <div></div>
    <div></div>
    <p>Hover over me</p>
</div>
<div class="move focus animate" tabindex="-1">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <p>Click on me</p>
</div>

答案 1 :(得分:-3)

尝试在您的子元素中使用css position: relative? 并使用宽度和高度的百分比。

相关问题