美文网首页
socket中的随意拖拽

socket中的随意拖拽

作者: 我就是心虚 | 来源:发表于2017-11-02 10:41 被阅读0次

    首先要配置node.js 的运行环境
    1、在app.js中设置引入socket.io文件

    var express = require('express');
    var app = express();
    var server = require('http').Server(app);(自己添加的)
    var io = require('socket.io')(server);(自己添加的)
    

    2、在HTML中定义一个块元素

    【html代码片段】
    <div id="box"></div>
    【js代码片段】
    var socket = io.connect('http://localhost:9000');
          var old = {};
          var oldX = box.offsetLeft;
          var oldY = box.offsetTop;
          box.onmousedown = function(e){
                var elX = e.clientX;
                var elY = e.clientY;
                oldX = box.offsetLeft;
                oldY = box.offsetTop;
                socket.emit("pos",{"elX":elX,"elY":elY});
                document.onmousemove = function(e){
                    var l = e.clientX;
                    var t = e.clientY;
                    socket.emit("cur",{"l":l,"t":t})
                }
                document.onmouseup = function(){
                          document.onmousedown = null;
                          document.onmousemove = null;
                  }
          }
          socket.on("position",function(data){
                old = data;
          })
          socket.on("curpos",function(data){
                box.style.left = oldX+data.l-old.elX + "px"
                box.style.top = oldY+data.t-old.elY + "px"
          })
    

    3、在app.js中

    io.on('connection', function (socket) {
        socket.on("pos",function(data){
          io.emit("position",data)
        });
        socket.on("cur",function(data){
          io.emit("curpos",data)
        })
    });
    
    server.listen(9000);
    

    相关文章

      网友评论

          本文标题:socket中的随意拖拽

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