这是jQuery UI可排序/可拖动的问题,如果被拖动的元素使用margin:0 auto对中,则拖动从容器的左侧开始,而不是元素实际所在的中心.
下面是一个演示来表明我的意思:http://codepen.io/anon/pen/YqWRvV.只需拖动红色方块.
如果从’.drag’元素中删除margin:0 auto,您将看到拖动正常开始.
我怎样才能解决这个问题,让我的元素从使用margin:0 auto中心时的实际位置拖动?
这似乎发生在Google Chrome中.
$( “#C”)排序();
`.drag { margin: 0 auto; width: 200px; height: 200px; background-color: red;}`
使用CSS’calc’使元素居中可以解决问题,但我的元素宽度可以动态改变. ‘calc’也不像’margin’那样得到支持.
将draggable包装在容器中可以解决问题,但HTML更改不是我正在寻找的解决方案.
更新:
所以这不是一个jQuery错误.这是谷歌Chrome的一个错误.显然,chrome会检索错误的位置,因此jQuery会从chrome告诉它元素所在的位置开始拖动.我在控制台中输出元素的左侧位置,当它显然不是时,您可以看到它是13px. http://codepen.io/anon/pen/YqWRvV.我想知道这个bug是否已被报道.
解
http://codepen.io/anon/pen/MyjeJP感谢JulienGrégoire
注意:此解决方案可能需要一种刷新帮助程序位置的方法.
解决方法:
Chrome返回的位置与Firefox不同,但您可以使用偏移量获得正确的坐标,这是可排序使用的.问题是在mouseStart上,边距会从计算中移除,这可能在您设置边距时有意义.但是有了自动余量,就会产生这个问题.
您可以添加一个选项来忽略边距并修改_mouseStart.像这样:
$("#c").sortable({ ignoreMargins: true});$.ui.sortable.prototype._mouseStart = function(event, overrideHandle, noActivation) { ... if (!this.options.ignoreMargins) { this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; } ...}
http://codepen.io/anon/pen/BKzeMp
编辑:
如果您不想修改插件,则可以使用start和stop事件.一个问题是很难检查边距是否已设置为自动,因此您可以在可排序的调用中定义它们,这不像它应该的那样灵活,或者您找到一种方法来检查哪些边距是自动动态的.
$("#c").sortable({ start: function(e, ui) { var marginsToSet = ui.item.data().sortableItem.margins; // You set the margins here, so they don't go back to 0 // once the item is put in absolute position ui.item.css('margin-left', marginsToSet.left); ui.item.css('margin-top', marginsToSet.top); }, stop: function(e, ui) { // Then you need to set the margins back once you stop dragging. // Ideally this should be dynamic, but you have to be able // to check which margins are set to auto, which as you'll // see if you look for some answers on this site, // doesn't look that simple. ui.item.css('margin', '20px auto'); }});
联系客服