此问题与RXJS相关。我正在尝试修改github中的拖放示例,使其适用于div类,而不仅仅是单个元素ID。https://github.com/Reactive-Extensions/RxJS/blob/master/examples/dragndrop/dragndrop.html
为div提供类或ID的简单更改不起作用,并且我失去了拖动元素的能力
3个简单的改变:
HTML line 7 i.e. <div class="dragTarget">Drag Me!</div>
CSS line 1 i.e. .dragTarget { style attributes unchanged }
JS line 4 i.e var dragTarget = document.getElementsByClassName('dragTarget');我还不够熟练,不知道这是不是RXJS中的一个bug,或者这个例子还不够通用。关于RXJS事件的文档建议这些更改应该足够了。感谢您的帮助。谢谢。
发布于 2015-05-19 07:39:44
fromEvent将使用传递给它的任何对象的on和off方法,否则它将使用addEventListener和removeEventListener。因此,如果您使用的是jQuery,您可以简单地选择所有它们并使用它(例如Observable.fromEvent($('.targetNode'), 'mouseup'))。
否则,您可以使用带有on和off方法的任何对象来订阅或取消订阅事件,就像我在下面所做的那样。
除此之外,您还可以在每个流中获取的MouseEvent对象上使用target属性来获取要移动的实际DOM节点……
下面的例子应该可以解决这个问题。
(function (global) {
/**
selectNodes is a method to select a NodeList, but convert it to
a type that has `on` and `off` methods RxJS 2 expects to see for `fromEvent`
*/
function selectNodes(selector) {
var nodes = document.querySelectorAll(selector);
return {
// the selected nodes
nodes: [].slice.call(this.nodes),
// subscribe to an event on every selected node
on: function(eventName, handler) {
this.nodes.forEach(function(node) { node.addEventListener(eventName, handler); });
},
// unsubscribe from the event on every selected node
off: function(eventName, handler) {
this.nodes.forEach(function(node) { node.removeEventListener(eventName, handler); });
}
};
}
function main () {
// IMPORTANT CHANGE: Use the selectNodes method we made
var dragTargets = selectNodes('.dragTarget');
// Get the three major events
var mouseup = Rx.Observable.fromEvent(dragTargets, 'mouseup');
var mousemove = Rx.Observable.fromEvent(document, 'mousemove');
var mousedown = Rx.Observable.fromEvent(dragTargets, 'mousedown');
var mousedrag = mousedown.flatMap(function (md) {
// calculate offsets when mouse down
var startX = md.offsetX, startY = md.offsetY;
// Calculate delta with mousemove until mouseup
return mousemove.map(function (mm) {
mm.preventDefault();
return {
left: mm.clientX - startX,
top: mm.clientY - startY,
target: mm.target, // IMPORTANT CHANGE: the element you care about
};
}).takeUntil(mouseup);
});
// Update position
var subscription = mousedrag.subscribe(function (d) {
d.target.style.top = d.top + 'px';
d.target.style.left = d.left + 'px';
});
}
main();
}(window));https://stackoverflow.com/questions/30080605
复制相似问题