jQuery UI可排序/可拖动存在一个问题,如果要拖动的元素使用margin:0 auto
以中心为中心,则拖动开始于容器的左侧,而不是元素真正所在的中心。
这里有一个演示来展示我的意思:http://codepen.io/anon/pen/YqWRvV。只需拖动红色方块即可。
如果从‘margin:0 auto
’元素中删除.drag,您将看到拖动正常启动。
如何解决此问题并使元素从使用margin:0 auto
对齐时的实际位置拖动
这似乎发生在谷歌Chrome上。
$("#c").sortable();
`.drag {
margin: 0 auto;
width: 200px;
height: 200px;
background-color: red;
}`
将元素与CSS 'calc‘对齐可以解决问题,但我的元素宽度可以动态变化。此外,“calc”没有“利润率”那么好的支持。
将可拖动的内容包装在容器中可以解决这个问题,但是HTML更改不是我想要的解决方案。
更新:,所以这不是jQuery错误。这是google chrome的一个bug。显然,铬检索到了错误的位置,因此jQuery从铬元素所在的位置开始拖动。我在控制台中输出元素的左边位置,当它显然不是. http://codepen.io/anon/pen/YqWRvV时,您可以看到它是13‘t。我想知道这个窃听器是否被报告了。
http://codepen.io/anon/pen/MyjeJP感谢Julienégoire备注:此解决方案可能需要一种刷新助手职位的方法。
发布于 2016-03-12 02:38:32
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事件。一个问题是,很难检查是否已将页边距设置为auto,因此您可以在可排序调用中定义它们,这不像应该的那样灵活,或者您找到了一种方法来动态地检查哪个边距是自动的。
$("#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');
}
});
http://codepen.io/anon/pen/mPrdYp
发布于 2016-03-08 17:43:09
嘿,我正在测试你的Codepen,并在两个不同的浏览器(Mozilla & Chrome)中检查它。
你说的是关于Chrome的东西。但在Mozilla,效果很好。
在铬的位置左属性值是不同的。意思是在Mozilla中,它的左边是:560 it,而在Chrome中,它是从左开始的: 0;
这就是为什么从左侧显着地显示拖放元素的原因。
我希望它能帮到你。
发布于 2016-03-08 18:04:24
更新您的jQuery以添加克隆助手:
$("#c").sortable({
helper: "clone"
});
并更新CSS以添加位置和溢出:
#c {
width: 100%;
padding: 50px 0px;
border: solid 5px;
box-sizing: border-box;
overflow: hidden;
position: relative;
}
更新的Codepen
https://stackoverflow.com/questions/35874038
复制相似问题