码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript + rxjs] Simple drag and drop with Observables

时间:2015-06-30 23:16:05      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:

Armed with the map and concatAll functions, we can create fairly complex interactions in a simple way. We will use Observable to create a simple drag and drop example with basic DOM elements.

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body, html, div, span, p, button, img, hr{
            border: 0;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>

<div id="parent" style="width: 300px; height: 300px; background: red; position: relative;">
    <div id="widget" style="width: 150px; height: 30px; background: blue; position: absolute; left: 150px; top: 150px;">Drag me</div>
</div>

<script src="//cdnjs.cloudflare.com/ajax/libs/rxjs/2.3.22/rx.all.js"></script>
<script src="drag.js"></script>
</body>
</html>

 

var Observable = Rx.Observable;

var parent = document.getElementById(‘parent‘);
var widget = document.getElementById(‘widget‘);

var widgetMouseDown = Observable.fromEvent(widget, ‘mousedown‘);
var parentMouseMove = Observable.fromEvent(parent, ‘mousemove‘);
var parentMouseUp = Observable.fromEvent(parent, ‘mouseup‘);

//.map() will create a tow-d array
//[1,2,3].map(function(num){return [3,4,5];}) -->>  [[3,4,5],[3,4,5],[3,4,5]]
var drags = widgetMouseDown
    .map(function(e) {
        return parentMouseMove.takeUntil(parentMouseUp);
    })
    .concatAll(); //flat to one-d array.

drags.forEach(function( e ) {
    widget.style.left = e.clientX + "px";
    widget.style.top = e.clientY + "px";
});

 

[Javascript + rxjs] Simple drag and drop with Observables

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/4611628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!