首先要配置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);
网友评论