jQuery UI可排序/可拖动存在一个问题,如果要拖动的元素使用居中margin:0 auto
,则拖动开始于容器的左侧,而不是元素实际位于的中心。
这是一个演示我的意思的演示:http : //codepen.io/anon/pen/YqWRvV。只需拖动红色方块即可。
如果margin:0 auto
从“ .drag”元素中删除,您将看到拖动正常开始。
如何在居中使用时解决此问题并使元素从实际位置拖动margin:0 auto
?
这似乎发生在Google Chrome中。
$("#c").sortable();
`.drag {
margin: 0 auto;
width: 200px;
height: 200px;
background-color: red;
}`
将元素与CSS'calc'居中即可解决此问题,但我的元素宽度可以动态更改。同样,“计算”不如“保证金”得到很好的支持。
将可拖动包装在容器中可以解决此问题,但是HTML更改并不是我想要的解决方案。
更新:所以这不是jQuery的错误。这是Google Chrome的错误。显然是chrome检索了错误的位置,因此jQuery从chrome告诉它元素所在的位置开始拖动。我在控制台中输出了该元素的左侧位置,您可以看到它显然不是13px。http://codepen.io/anon/pen/YqWRvV。我想知道是否已报告此错误。
解决方案 http://codepen.io/anon/pen/MyjeJP感谢JulienGrégoire注意:此解决方案可能需要一种刷新助手位置的方法。
Chrome返回的位置与Firefox不同,但是您可以使用offset获得正确的坐标,而offset是可排序的。问题在于,在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');
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句