這是jQuery UI可排序/可拖動(dòng)的問(wèn)題,如果被拖動(dòng)的元素使用margin:0 auto對中,則拖動(dòng)從容器的左側開(kāi)始,而不是元素實(shí)際所在的中心.
下面是一個(gè)演示來(lái)表明我的意思:http://codepen.io/anon/pen/YqWRvV.只需拖動(dòng)紅色方塊.
如果從’.drag’元素中刪除margin:0 auto,您將看到拖動(dòng)正常開(kāi)始.
我怎樣才能解決這個(gè)問(wèn)題,讓我的元素從使用margin:0 auto中心時(shí)的實(shí)際位置拖動(dòng)?
這似乎發(fā)生在Google Chrome中.
$( “#C”)排序();
`.drag { margin: 0 auto; width: 200px; height: 200px; background-color: red;}`使用CSS’calc’使元素居中可以解決問(wèn)題,但我的元素寬度可以動(dòng)態(tài)改變. ‘calc’也不像’margin’那樣得到支持.
將draggable包裝在容器中可以解決問(wèn)題,但HTML更改不是我正在尋找的解決方案.
更新:
所以這不是一個(gè)jQuery錯誤.這是谷歌Chrome的一個(gè)錯誤.顯然,chrome會(huì )檢索錯誤的位置,因此jQuery會(huì )從chrome告訴它元素所在的位置開(kāi)始拖動(dòng).我在控制臺中輸出元素的左側位置,當它顯然不是時(shí),您可以看到它是13px. http://codepen.io/anon/pen/YqWRvV.我想知道這個(gè)bug是否已被報道.
解
http://codepen.io/anon/pen/MyjeJP感謝JulienGrégoire
注意:此解決方案可能需要一種刷新幫助程序位置的方法.
解決方法:
Chrome返回的位置與Firefox不同,但您可以使用偏移量獲得正確的坐標,這是可排序使用的.問(wèn)題是在mouseStart上,邊距會(huì )從計算中移除,這可能在您設置邊距時(shí)有意義.但是有了自動(dòng)余量,就會(huì )產(chǎn)生這個(gè)問(wèn)題.
您可以添加一個(gè)選項來(lái)忽略邊距并修改_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事件.一個(gè)問(wèn)題是很難檢查邊距是否已設置為自動(dòng),因此您可以在可排序的調用中定義它們,這不像它應該的那樣靈活,或者您找到一種方法來(lái)檢查哪些邊距是自動(dòng)動(dòng)態(tài)的.
$("#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'); }});
聯(lián)系客服