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

Draggable squarerectangle that snaps to grid in JQueryJavascript - Stack Overflow

programmeradmin2浏览0评论

I want to create a rectangle on mousedown that drags across a grid and remains there on mouseup, snapping to the gridlines and outputting the coordinates for top left and bottom right of the it's position (x1,x2,y1,y2). Any help on starting to build this would be much appreciated.

I have a 500x500 grid with squares of 10x10 (example - jsFiddle).

Grid Code:

      function creategrid(size){

          var standardW = Math.floor((500) / size),
              standardH = Math.floor((500) / size);

          var standard = document.createElement('div');
              standard.className = 'grid';
              standard.style.width = (standardW * size) + 'px';
              standard.style.height = (standardH * size) + 'px';

            for (var i = 0; i < standardH; i++) {
                for (var p = 0; p < standardW; p++) {
                  var cell = document.createElement('div');
                      cell.style.height = (size - 1) + 'px';
                      cell.style.width = (size - 1) + 'px';
                      cell.style.position = 'relative'
                      cell.style.zIndex= '2';
            standard.appendChild(cell);
                }
            }

          document.body.appendChild(standard);
      }

      creategrid(10);

CSS for grid:

  .grid {
    margin: 0px auto auto;
    border: 1px solid #000;
    border-width: 0 1px 1px 0;
    background-color: #CCC;
  }

  .grid div {
    border: 1px solid #000;
    border-width: 1px 0 0 1px;
    float: left;
  }

  #tooltip { 
    text-align:center; 
    background:black; 
    color:white; 
    padding:3px 0; 
    width:150px; 
    position:fixed; 
    display:none; 
    white-space:nowrap;
    z-index:3; 
  }

I've found some snapping code through google but I am literally stuck (I'm a plete beginner at JQuery).

Alternatively if anyone has a better idea of how to do this then that would be more than wele.

  • Some background if you want to suggest a different way to do it: This is for a website running off of an SQL server built in python and django. The data it outputs are jSON objects but otherwise I'm just using html, css and javacript/jQuery for the front end. -- Not sure if that info is useful or not.

EDIT added code for mouseover grid coordinates in jQuery

    $(window).load(function() {
        var tooltip = $('<div id="tooltip">').appendTo('body')[0];

        $('.coords').
        each(function() {

            var pos = $(this).offset(),
                top = pos.top,
                left = pos.left,
                width = $(this).width(),
                height = $(this).height();

            $(this).
            mousemove(function(e) {
                var x = ((e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - left).toFixed(0),
                    y = (((e.clientY + document.body.scrollTop + document.documentElement.scrollTop) - top)).toFixed(0);

                    $(tooltip).text( x + ', ' + y).css({
                        left: e.clientX + 20,
                        top: e.clientY + 10
                    }).show();

            }).

            mouseleave(function() {
                $(tooltip).hide();
            });

        });

    });

I want to create a rectangle on mousedown that drags across a grid and remains there on mouseup, snapping to the gridlines and outputting the coordinates for top left and bottom right of the it's position (x1,x2,y1,y2). Any help on starting to build this would be much appreciated.

I have a 500x500 grid with squares of 10x10 (example - jsFiddle).

Grid Code:

      function creategrid(size){

          var standardW = Math.floor((500) / size),
              standardH = Math.floor((500) / size);

          var standard = document.createElement('div');
              standard.className = 'grid';
              standard.style.width = (standardW * size) + 'px';
              standard.style.height = (standardH * size) + 'px';

            for (var i = 0; i < standardH; i++) {
                for (var p = 0; p < standardW; p++) {
                  var cell = document.createElement('div');
                      cell.style.height = (size - 1) + 'px';
                      cell.style.width = (size - 1) + 'px';
                      cell.style.position = 'relative'
                      cell.style.zIndex= '2';
            standard.appendChild(cell);
                }
            }

          document.body.appendChild(standard);
      }

      creategrid(10);

CSS for grid:

  .grid {
    margin: 0px auto auto;
    border: 1px solid #000;
    border-width: 0 1px 1px 0;
    background-color: #CCC;
  }

  .grid div {
    border: 1px solid #000;
    border-width: 1px 0 0 1px;
    float: left;
  }

  #tooltip { 
    text-align:center; 
    background:black; 
    color:white; 
    padding:3px 0; 
    width:150px; 
    position:fixed; 
    display:none; 
    white-space:nowrap;
    z-index:3; 
  }

I've found some snapping code through google http://jqueryui./draggable/#snap-to but I am literally stuck (I'm a plete beginner at JQuery).

Alternatively if anyone has a better idea of how to do this then that would be more than wele.

  • Some background if you want to suggest a different way to do it: This is for a website running off of an SQL server built in python and django. The data it outputs are jSON objects but otherwise I'm just using html, css and javacript/jQuery for the front end. -- Not sure if that info is useful or not.

EDIT added code for mouseover grid coordinates in jQuery

    $(window).load(function() {
        var tooltip = $('<div id="tooltip">').appendTo('body')[0];

        $('.coords').
        each(function() {

            var pos = $(this).offset(),
                top = pos.top,
                left = pos.left,
                width = $(this).width(),
                height = $(this).height();

            $(this).
            mousemove(function(e) {
                var x = ((e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft) - left).toFixed(0),
                    y = (((e.clientY + document.body.scrollTop + document.documentElement.scrollTop) - top)).toFixed(0);

                    $(tooltip).text( x + ', ' + y).css({
                        left: e.clientX + 20,
                        top: e.clientY + 10
                    }).show();

            }).

            mouseleave(function() {
                $(tooltip).hide();
            });

        });

    });
Share Improve this question edited Jan 29, 2013 at 3:06 Cameron Guthrie asked Jan 29, 2013 at 2:17 Cameron GuthrieCameron Guthrie 1411 silver badge9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

If i understood your question correctly, you don't really need jQueryUI for that. You need to find mouse position snapped to the cell of the grid on mousemove and resize your selection rectangle.

function getMousePos (e) {
  return {
    'left': Math.floor((e.pageX - gridOffset.left) / cellSpacing) * cellSpacing,
    'top': Math.floor((e.pageY - gridOffset.top) / cellSpacing) * cellSpacing
  }
}

Here is an example - http://jsfiddle/4efTV/

I remend you to use that plugin, jQuery UI, its really simple to use take a look at this fiddle: http://jsfiddle/promatik/hBQxb/

HTML

<div class="snap-box">snap box</div>

Javascript:

$( ".snap-box" ).draggable({ grid: [ 10,10 ] });

CSS:

.snap-box {
    width: 50px;
    height: 50px;
    position: absolute;
    z-index: 10;
}
发布评论

评论列表(0)

  1. 暂无评论