前言:发现一个很有趣的关于transform的bug。
一、问题起始:
①、要弄一个侧边展开栏,我是直接给body添加一个transform:translateX(80%);的样式,让body整体往左移了80%的距离
②、然后点击侧边展开栏再给body添加一个transform:translateX(0);的样式,让他回到原来位置。
③、整体的效果实现并没有问题。
④、但是fixed定位在底部的导航条"消失了",底部的fixed定位失效了。
⑤、而且fixed定位在头部的导航条也失去了效果。不再跟随页面内容滚动了。
二、问题还原
<style>
.content { width:100%; height:200vh; background:#ccc; }
.topBar { position:fixed; top:20px; left:0; width:100%; height:50px; background:red; }
.footBar{ position:fixed; bottom:0; left:0; width:100%; height:50px; background:red; }
</style>
<body style="margin:0;">
<div class="content"></div>
<div class="topBar" style=""></div>
<div class="footBar" style=""></div>
</body>
添加transform:translateX(0);
<style>
.content { width:100%; height:200vh; background:#ccc; }
.topBar { position:fixed; top:20px; left:0; width:100%; height:50px; background:red; }
.footBar{ position:fixed; bottom:0; left:0; width:100%; height:50px; background:red; }
</style>
<body style="margin:0; transform:translateX(0);">
<div class="content"></div>
<div class="topBar" style=""></div>
<div class="footBar" style=""></div>
</body>
这时就会发现上述问题了。
三、问题扩展
①、transform:translateX()使fixed定位失去效果,是不是使用了,其他定位(absolute,relative),就会失去效果?
<div style="position:relative; width:500px; height:300px; overflow-Y:auto; overflow-X:hidden;">
<div style="width:500px; height:500px; background:#ccc; transform:translateX(0px);"></div>
<div style="width:500px; height:50px; background:red; position:absolute; left:0; bottom:0;"></div>
</div>
运行后发现,定位在div底部的导航条并没有消失?(只是absolute定位并没有失去效果)
如果认真会发现(二、问题还原中,我把topBar顶部的导航条的top设置了20px),然后topBar还是保留着距离头部20px的距离,这时可以猜想是fixed定位变成了absolute定位了!!!
通过其他实验,发现不只是translate(),还有scale(),rotate()都会使fixed定位失效。
四、解决问题
<style>
.content { width:100%; height:200vh; background:#ccc; }
.topBar { position:fixed; top:20px; left:0; width:100%; height:50px; background:red; }
.footBar{ position:fixed; bottom:0; left:0; width:100%; height:50px; background:red; }
.tansform { transform:translateX(80%); }
</style>
<body style="margin:0;" class="tansform">
<div class="content"></div>
<div class="topBar" style=""></div>
<div class="footBar" style=""></div>
</body>
我是通过添加类和移除类,来解决这问题。
也可以通过给里面的内容添加transform:translateX()
<style>
.content { width:100%; height:200vh; background:#ccc; }
.topBar { position:fixed; top:20px; left:0; width:100%; height:50px; background:red; }
.footBar{ position:fixed; bottom:0; left:0; width:100%; height:50px; background:red; }
</style>
<body style="margin:0; width:100%;">
<div class="content" style="transform:translateX(80%)"></div>
<div class="topBar" style=""></div>
<div class="footBar" style=""></div>
</body>
不管怎么说,还是要小心使用transform