• [Javascript + rxjs] Simple drag and drop with Observables


    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=" 300px; height: 300px; background: red; position: relative;">
        <div id="widget" style=" 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";
    });
  • 相关阅读:
    MCU 51-7 I2C Communication EEPROM
    FinalShell(免费的XShell替代品)
    Docker部署Redis
    Docker-Compose部署ELK
    Linux清空文件
    Linux防火墙的操作
    VSCode远程连接Linux服务器
    Apollo分布式配置中心
    SpringBoot整合log4j2
    MySQL区分大小写
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4611628.html
Copyright © 2020-2023  润新知