最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Panning DIV element around using javascript - Stack Overflow

programmeradmin1浏览0评论

I am trying to have a div in a container which when the user clicks and drags somewhere in the document area, the .room element pans around inside the .viewport element by holding down the middle click button.

Here is the issue: (Hold right click for this one, middle click didn't work for some reason) /

JS

var mouseX = 0;
var mouseY = 0;
var scale = 1.0;

$(document).mousemove(function (e) {

    var offset = $('.room').offset();

    //relative mouse x,y
    mouseX = parseFloat((e.pageX - offset.left) / scale, 2);
    mouseY = parseFloat((e.pageY - offset.top) / scale, 2);

    //absolute mouse x,y
    mouseXRaw = e.pageX;
    mouseYRaw = e.pageY;

    $(".room").html(mouseX + ', ' + mouseY + '<br />Right click document and pan');

    switch (e.which) {
        case 3:
            $('.room').css({
                left: mouseX,
                top: mouseY
            });
            break;
    }
    return true;
});

$(document).on('contextmenu', function () {
    return false;
});

I am trying to have a div in a container which when the user clicks and drags somewhere in the document area, the .room element pans around inside the .viewport element by holding down the middle click button.

Here is the issue: (Hold right click for this one, middle click didn't work for some reason) http://jsfiddle/JeZj5/2/

JS

var mouseX = 0;
var mouseY = 0;
var scale = 1.0;

$(document).mousemove(function (e) {

    var offset = $('.room').offset();

    //relative mouse x,y
    mouseX = parseFloat((e.pageX - offset.left) / scale, 2);
    mouseY = parseFloat((e.pageY - offset.top) / scale, 2);

    //absolute mouse x,y
    mouseXRaw = e.pageX;
    mouseYRaw = e.pageY;

    $(".room").html(mouseX + ', ' + mouseY + '<br />Right click document and pan');

    switch (e.which) {
        case 3:
            $('.room').css({
                left: mouseX,
                top: mouseY
            });
            break;
    }
    return true;
});

$(document).on('contextmenu', function () {
    return false;
});
Share Improve this question asked Mar 5, 2014 at 2:13 user780756user780756 1,4843 gold badges21 silver badges33 bronze badges 1
  • You should watch the mousedown event and then track movement instead of watching all the mouse movement and then seeing if the mouse is down. – Alexander Mistakidis Commented Mar 5, 2014 at 2:36
Add a ment  | 

1 Answer 1

Reset to default 5

This should be more along the lines of what you're looking for. Key change:

delta.x = e.pageX - drag.x;
delta.y = e.pageY - drag.y;

Using the delta to change the position. The .room's position should be moving with respect to it's current location, minus the mouse drag position (not the other way around).

http://jsfiddle/X2PZP/3/

发布评论

评论列表(0)

  1. 暂无评论