【问题标题】:Socket.io - dragging DIV by multiple users not workingSocket.io - 多个用户拖动 DIV 不起作用
【发布时间】:2021-01-05 22:25:21
【问题描述】:

我正在尝试在我的网页上使用它。但是当我在两个不同的网络浏览器中打开网页时,当我拖动 div 时,它不会在两者上更新,只是我正在拖动的那个。下面是我正在使用的代码。为什么这不起作用?

下面是我http://mywebsite.com/myProject/ 中的 index.html

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
  <script src="socket.io.js"></script>
  <script>
    $(document).ready(function () {
      var socket = io("http://mywebsite.com/myProject/");
      socket.on('update_position', function (data) {
        var x = data.x;
        var y = data.y;
        // jquery code to move div here
        $("#left").val(x);
        $("#top").val(y);
        $("#mydiv").css({
          left: x + "px",
          top: y + "px"
        });
      });

      $("#mydiv").draggable({
        drag: function (event, ui) {
          var coord = $(this).position();
          $("#left").val(coord.left);
          $("#top").val(coord.top);
          socket.emit('receive_position', {
            x: coord.left,
            y: coord.top
          });
        }
      });

    });
  </script>
  <style> 
    .dstyle
    {
        position: absolute;
        width: 50px; height: 50px;
        background: #ffb; padding: 5px;
        border: 2px solid #999;
    }
  </style>
</head>
<body>
  X: <input type="text" id="left"/>
  Y: <input type="text" id="top"/>

  <div id="mydiv" class="dstyle">drag me</div>
</body>

下面是server.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

var lastPosition = { x: 0, y: 0 }; // whatever default data

io.sockets.on('connection', function (socket) {
  socket.emit('update_position', lastPosition);
  socket.on('receive_position', function (data) {
     lastPosition = data;
     socket.broadcast.emit('update_position', data); // send `data` to all other clients
  });
});

【问题讨论】:

    标签: html jquery socket.io


    【解决方案1】:

    问题解决了!问题是我的虚拟主机不支持 Node JS,所以现在我使用的是 glitch.com,它提供支持 Node JS 的免费主机

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      相关资源
      最近更新 更多