我想在 mousedown 上创建一个矩形,它在网格上拖动并在 mouseup 上保持在那里,捕捉到网格线并输出其位置左上角和右下角的坐标 (x1,x2,y1,y2)。非常感谢任何有关开始构建它的帮助。
我有一个 500x500 的网格和 10x10 的正方形(示例 - jsFiddle)。
网格代码:
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:
.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;
}
我通过谷歌找到了一些捕捉代码 http://jqueryui.com/draggable/#snap-to但我真的被卡住了(我是 JQuery 的初学者)。
或者,如果有人对如何执行此操作有更好的想法,那将非常受欢迎。
- 如果您想建议一种不同的方法,请了解一些背景知识:这是一个运行在 python 和 django 中构建的 SQL 服务器的网站。它输出的数据是 jSON 对象,但除此之外我只是在前端使用 html、css 和 javacript/jQuery。 -- 不确定该信息是否有用。
编辑 在 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();
});
});
});
最佳答案
如果我正确理解了您的问题,那么您实际上并不需要 jQueryUI。 您需要在 mousemove 上找到捕捉到网格单元格的鼠标位置,并调整选择矩形的大小。
function getMousePos (e) {
return {
'left': Math.floor((e.pageX - gridOffset.left) / cellSpacing) * cellSpacing,
'top': Math.floor((e.pageY - gridOffset.top) / cellSpacing) * cellSpacing
}
}
这是一个例子 - http://jsfiddle.net/4efTV/
关于javascript - 在 JQuery/Javascript 中捕捉到网格的可拖动正方形/矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14574618/