[英]Set the origin of element to center instead of top left (jquery)
I have this marker (which is a simple div) inside the triangle:我在三角形内有这个标记(这是一个简单的 div):
The center of the marker should lie exactly in the centroid of the triangle.标记的中心应恰好位于三角形的质心。
As seen in the picture, it's not exactly in the centroid (it's a bit to the right, and possible to the bottom).如图所示,它并不完全位于质心(它有点向右,可能在底部)。
I'm using jquery ui .draggable
method.我正在使用 jquery ui
.draggable
方法。 Here is my css for the marker:这是我的标记 css:
#marker {
position: absolute;
background: #808080;
border-radius: 50%;
width: 50px;
height: 50px;
cursor: grab;
}
And here's my jquery script:这是我的 jquery 脚本:
$(document).ready(function () {
var triangle = $("#triangle");
var marker = $("#marker");
var coord = getTriangleCoordinates(triangle);
var center = centroid(coord);
$("#marker").hover(
function () {
// over
$(this).css("filter", "brightness(0.8)");
},
function () {
// out
$(this).css("filter", "brightness(1)");
}
);
$("#marker").mouseup(function () {
$(this).css("background", "salmon");
});
$("#marker").draggable({
drag: function (event, ui) {
var offset = ui.offset;
if (!bounded(offset, coord)) return false;
}
});
marker.css("left", Math.round(center.left) - 5 + "px");
marker.css("top", Math.round(center.top) - 5 + "px");
console.log(coord);
});
How do I make the default position of the marker's center exactly in the centroid, while still being able to drag the marker?如何使标记中心的默认值 position 正好位于质心,同时仍然能够拖动标记?
I tried the transform: translate(-50%, 0)
css property.我尝试了
transform: translate(-50%, 0)
css 属性。 Although it fixed the position, it messed up the dragging feature altogether.虽然它修复了 position,但它完全搞砸了拖动功能。
Any help is appreciated.任何帮助表示赞赏。 Thanks!!
谢谢!!
Your marker element has width 50px and height 50px.您的标记元素的宽度为 50 像素,高度为 50 像素。
Assuming your centroid function returns the correct result, you are then positioning the top left corner of the marker (remember, it is basically a square) at a mere 5px offset from the actual centroid.假设您的质心 function 返回正确的结果,然后您将标记的左上角(记住,它基本上是一个正方形)定位在距离实际质心仅 5px 的偏移处。
It needs to be offset by half its width and height so that its central point is at the centroid.它需要偏移其宽度和高度的一半,以便其中心点位于质心。
So change this:所以改变这个:
marker.css("left", Math.round(center.left) - 5 + "px");
marker.css("top", Math.round(center.top) - 5 + "px");
To this:对此:
marker.css("left", Math.round(center.left) - 25 + "px");
marker.css("top", Math.round(center.top) - 25 + "px");
For a more general solution, if for example the dimensions of the marker might change with viewport size or something, you can set the top left to the centroid and then transform: translate(-50%, 50%)
.对于更通用的解决方案,例如,如果标记的尺寸可能会随着视口大小或其他因素而变化,您可以将左上角设置为质心,然后进行
transform: translate(-50%, 50%)
。 This will move the marker left and up by half its own width and height, whatever they are.这会将标记向左和向上移动其宽度和高度的一半,无论它们是什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.