使用jQuery .show()与.toggle('explode')时如何避免DIV左右偏移?
解决jQuery show()和toggle('explode')时元素左右偏移的问题
我看了你的代码和遇到的问题——元素在执行show()淡入和toggle('explode')爆炸隐藏时会出现左右移动的情况,这其实是因为你用了table-cell来实现居中布局,而jQuery UI的动画在处理这类布局元素时容易出现布局计算偏差。
问题原因
display: table-cell的居中效果依赖父级的table布局上下文,当jQuery执行show()或者toggle('explode')动画时,会临时修改元素的display属性(比如show()过程中可能先把元素切换为block状态再执行淡入动画),这就打破了原本的table布局逻辑,导致元素位置发生偏移。
解决方案
把#golden_particlesDiv的display: table-cell改成display: block,然后用margin: 0 auto来实现水平居中,这种常规的块级元素居中方式,在动画过程中布局上下文更稳定,不会出现偏移问题。
修改后的完整代码如下:
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <div style="width:100%; position:relative; top:10px; right:30px; color:white; font-size:40pt; line-height:1.5em;"> <div style="display: table; position:absolute; top:0px; width:100%;"> <div id="golden_particlesDiv" style="display: block; text-align:center; margin:0 auto; display:none;"> <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" style="width:322px; height:322px;"> </div> </div> </div> <script> $(document).ready(function() { $("#golden_particlesDiv").show(2000).toggle( "explode", {pieces: 25}, 1000 ); }); </script> </body> </html>
效果说明
修改后,元素会始终保持在居中位置完成淡入显示,爆炸隐藏的动画也不会再出现左右移动的问题,两种动画都能正常执行且位置稳定。
内容的提问来源于stack exchange,提问作者Xen Xu
相关产品推荐
相关产品推荐

