我正在尝试按照html5拖放教程here . 我无法在 rect
元素上注册 dragstart
事件 . 如果我将事件从 draggable
更改为 mousedown
,则会调用 handleDragStart
处理程序 . 请忽略代码中的其他空白注册 .
JSFiddle here
<!DOCTYPE html>
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<style type="text/css" media="screen">
svg rect { cursor: move; }
</style>
</head><body>
<h1>SVG/HTML 5 Example</h1>
<svg id="cvs">
<rect draggable="true" x="0" y="10" width="100" height="80" fill="#69c" />
<rect x="50" y="50" width="90" height="50" fill="#c66" />
</svg>
<script type="text/javascript" src="loc.js"></script>
</body></html>
loc.js
$(document).ready(function() {
function handleDragStart(e) {
log("handleDragStart");
this.style.opacity = '0.4'; // this ==> e.target is the source node.
};
var registercb = function () {
$("#cvs > rect").each(function() {
$(this).attr('draggable', 'true');
});
$("#cvs > rect").bind('dragstart', handleDragStart);
$(window).mousedown(function (e) {
});
$(window).mousemove(function (e) {
});
$(window).mouseup(function (e) {
log("mouseup");
});
};
function log() {
if (window.console && window.console.log)
window.console.log('[XXX] ' + Array.prototype.join.call(arguments, ' '));
};
registercb();
});
2 回答
此行为可能由以下几个原因引起:
HTML 5拖放是一团糟,according to this article . 我知道它有点老了,但这个问题似乎还没有解决
jQuery不支持SVG DOM模型 . 因此,它的某些部分可能有效,有些则无效(如
offset()
或width()
) .我现在绝对不依赖于HTML5拖放支持,而是使用库来处理这个问题 . 如果您想使用SVG,可以尝试Raphaël . 如果你也需要jQuery,也许SVG plugin是可行的方法 . 请注意,目前这两个项目都没有积极开发 . 我知道这不是一个令人满意的答案,但我也必须学习,jQuery和SVG并不能很好地结合在一起 . 希望有人证明我错了;) .
我知道这是一个老问题,我从this other question到达这里,被标记为这个的副本,并希望添加一个不需要jQuery或任何库的可能解决方案,并且适用于所有主流浏览器 . 它基于@AmirHossein Mehrvarzi推荐的this tutorial .
这个小解决方案不使用拖动事件,只有
mousedown
,mouseup
和mousemove
. 这是它的工作原理:当鼠标在矩形上向下时,它会保存鼠标位置和活动元素 .
当鼠标移动时,矩形坐标将使用新的鼠标位置进行更新 .
当鼠标向上时,它会重置活动元素 .
从上面问题中的代码:
你也可以在这个JSFiddle上看到它:http://jsfiddle.net/YNReB/61/
如果要添加删除功能,可以修改
mouseup
函数以读取光标位置上的元素(使用document.elementFromPoint(e.clientX, e.clientY)
),然后可以对原始元素和删除它的元素执行操作 .