如何修复jQuery UI中垂直居中拖拽元素的偏移问题?
解决可拖拽元素垂直居中后无法正常设置top值的问题
问题根源在于margin: auto 0配合top:0; bottom:0的布局方式,会让浏览器自动计算margin值实现垂直居中,此时手动或拖拽插件设置的top属性会被覆盖,导致拖拽位置异常。以下是两种可靠的解决方法:
方法一:使用transform实现垂直居中
这种方式不依赖margin或top/bottom的自动计算,拖拽时插件修改的top/left值能正常生效:
<html> <head> <style> #draggablediv { width: 100px; height: 100px; background-color: yellow; position: absolute; /* 垂直居中:top设为50%,再向上偏移自身高度的50% */ top: 50%; transform: translateY(-50%); /* 如果需要水平居中,可添加以下两行 */ /* left: 50%; */ /* transform: translate(-50%, -50%); */ } </style> </head> <body> <div id="draggablediv"></div> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script> $(function () { $("#draggablediv").draggable(); }); </script> </body> </html>
方法二:手动计算初始垂直位置
通过JS计算容器(此处为窗口)高度与元素高度的差值,直接设置初始top值,完全避免margin:auto的干扰:
<html> <head> <style> #draggablediv { width: 100px; height: 100px; background-color: yellow; position: absolute; /* 移除margin和top/bottom的自动布局设置 */ } </style> </head> <body> <div id="draggablediv"></div> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script> $(function () { const $dragEl = $("#draggablediv"); // 计算并设置初始垂直居中位置 const windowHeight = $(window).height(); const elHeight = $dragEl.height(); $dragEl.css('top', (windowHeight - elHeight) / 2 + 'px'); $dragEl.draggable(); }); </script> </body> </html>
两种方法都能保证拖拽时元素的top值被正确设置,不会出现位置偏移问题。
内容的提问来源于stack exchange,提问作者tp1415926535
相关产品推荐
相关产品推荐

