全部,
我希望能够使用 translateX 为子元素设置 100% 的动画(即从左边缘到右边缘)。
挑战在于 translateX 中的百分比指的是元素本身,而不是父元素。
因此,例如,如果我的 html 如下所示:
<div id="parent">
<div id="child">
</div>
我的 CSS 是这样的(省略了供应商前缀):
#parent {
position: relative;
width: 300px;
height: 100px;
background-color: black;
}
#child {
position: absolute;
width: 20px;
height: 100px;
background-color:red;
transform: translateX(100%);
}
这是行不通的—— child 只移动 20px(100% 自身),而不是一直穿过父对象。 (你可以在 jsfiddle 上看到这个):
我能做到:
#child {
position: absolute;
width: 20px;
height: 100px;
background-color:red;
-webkit-transform: translateX(300px) translateX(-100%);
transform: translateX(300px) translateX(-100%);
}
这是可行的(参见 here again on jsfiddle ),因为它首先将子级移动 300px(父级的全宽),减去 20px(子级的宽度)。但是,这取决于具有固定的已知像素尺寸的父级。
但是,在我的响应式设计中——我不知道父级的宽度,它会改变。
我知道我可以使用 left:0 和 right:0,但是 left/right 的动画性能比 translateX ( Thanks Paul Irish! ) 差很多。
有办法吗?
提前致谢。
最佳答案
我最初没有发布我的想法,因为它涉及创建一个额外的 HTML 层,并期待更好的解决方案。
既然没有发生,我解释一下我的评论。我的意思是:
#parent {
position: relative;
width: 300px;
height: 100px;
background-color: black;
}
#wrapper {
position: absolute;
width: 100%;
height: 100px;
border: solid 1px green;
transition: all 1s;
}
#wrapper:hover {
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
#child {
position: absolute;
width: 20px;
height: 100px;
background-color:red;
}
#wrapper:hover #child {
-webkit-transform: translateX(-100%);
transform: translateX(-100%);
}
由于包装器是父级的 100% 宽度,因此将其转换为 100% 会按预期工作。
请注意,正如您所说,包装器已 100% 被翻译。但是,似乎您真正想要的是将元素移动 100% - 宽度。为实现这一点,您必须在相反的方向上也 100% 地平移子项(现在这适用于子项的宽度)。
更正: child 应该共享包装器的过渡属性:
#parent {
position: relative;
width: 300px;
height: 100px;
background-color: black;
}
#wrapper {
position: absolute;
width: 100%;
height: 100px;
border: solid 1px green;
transition: all 5s;
}
#wrapper:hover {
transform: translateX(100%);
}
#child {
position: absolute;
width: 50px;
height: 100px;
background-color:red;
transition: inherit;
}
#wrapper:hover #child {
transform: translateX(-100%);
}
<div id="parent">
<div id="wrapper">
<div id="child"></div>
</div>
</div>
关于html - 如何使用变换:translateX to move a child element horizontally 100% across the parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21557476/