CSS中有一种实现左右位移不动的方法,就是使用position属性的fixed定位和transform属性的translateX移动。
.container {
position: fixed;
top: 0;
left: 0;
width: 100%;
transform: translateX(0);
}
.left {
position: relative;
left: -100%;
width: 100%;
background-color: #ccc;
}
.right {
position: relative;
left: 100%;
width: 100%;
background-color: #eee;
}
.container.show-left .left {
left: 0;
}
.container.show-right .right {
left: 0;
} 这段代码中,我们将容器元素的position属性设置为fixed定位,使其可以在视口中固定不动。将左侧和右侧的元素利用relative定位并设置left属性,距离容器元素的左右侧各移动100%的距离,使其在视口外。使用transform属性的translateX(0)将容器元素移回原来的位置。
通过添加类名.show-left或.show-right实现左侧或右侧元素的出现和消失。使用left属性实现元素的平移。
这种方法虽然可以达到左右侧元素移动但容器元素不动的效果,但需要考虑兼容性问题,具体应用时需谨慎。