美文网首页Rx系列程序员
Rx.js实现拖拽效果

Rx.js实现拖拽效果

作者: 编码的哲哲 | 来源:发表于2018-06-23 11:04 被阅读67次

    周五用裸react写了波一个选择物品弹框拖拽的需求,不是很爽,所以周末用Rx又撸了一个,下面是功能完备的demo:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            #dragBox {
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                width: 200px;
                height: 200px;
                background: red;
                cursor: move;
            }
        </style>
    </head>
    <body>
        <div draggable="true" id="dragBox">可被拖拽的Box</div>
        <script src="./main.js"></script>
    </body>
    </html>
    
    import { fromEvent } from 'rxjs';
    import { map, tap, switchMap } from 'rxjs/operators';
    
    document.getElementsByTagName('body')[0].addEventListener('dragenter', e => e.preventDefault())
    document.getElementsByTagName('body')[0].addEventListener('dragover', e => e.preventDefault())
    
    const $dragBox = document.getElementById('dragBox');
    const DRAP_BOX_OFFSET = {
        x: $dragBox.clientWidth / 2,
        y: $dragBox.clientHeight / 2,
    }
    
    const generateDragStream = (type) => {
        return fromEvent($dragBox, type);
    }
    
    const dragStart$ = generateDragStream('dragstart').pipe(
        tap(e => {
            e.dataTransfer.setDragImage(document.createElement('div'), 0, 0)
        })
    )
    
    const dragMove$ = generateDragStream('drag').pipe(
        map(e => {
            return {
                clientX: e.clientX - DRAP_BOX_OFFSET.x,
                clientY: e.clientY - DRAP_BOX_OFFSET.y
            }
        })
    )
    
    dragStart$.pipe(
        switchMap(() => dragMove$)
    ).subscribe(v => {
        $dragBox.style.top = `${v.clientY}px`;
        $dragBox.style.left = `${v.clientX}px`;
    });
    

    效果:


    拖拽.gif

    要是想一起愉快的写Rx,来我们团队吧QAQ,简历发我邮箱chonger@qunhemail.com,帮你内推😆,妹子可以私信加我微信哦♪(*)啦啦~

    相关文章

      网友评论

      本文标题:Rx.js实现拖拽效果

      本文链接:https://www.haomeiwen.com/subject/iberyftx.html