[英]How to get the element position after css-translation
I wrote an angularJS directive for dragging elements, therefore I have a mousemove-handler: 我写了一个angularJS指令来拖动元素,因此有一个mousemove-handler:
function mousemove($event) {
var x = startX + $event.clientX - initialMouseX;
var y = startY + $event.clientY - initialMouseY;
var maxX = window.innerWidth - elm.prop('offsetWidth');
var maxY = window.innerHeight - elm.prop('offsetHeight');
x = (x < maxX) ? x : maxX;
y = (y < maxY) ? y : maxY;
elm.css({
top: y + 'px',
left: x + 'px'
});
return false;
}
I don´t want to drop the element out of the window. 我不想将元素从窗口中删除。 Therefore I want to use the variables maxX and maxY.
因此,我想使用变量maxX和maxY。 But what can I do, if the element is css-translated like this:
但是,如果元素像这样经过css转换,我该怎么办:
.my-element {
position: absolute;
left: 50%;
top: 50%;
width: 50%;
transform: translate(-50%, -50%);
}
Apply : 申请 :
var elmprop = getComputedStyle('idofelm', null);
Now you are able to get actual position of element and all other properties . 现在您可以获取element和所有其他属性的实际位置。
Like : 喜欢 :
elmprop.backgroundColor,
elmprop.top,
elmprop.left,
================================= =================================
Edit by Martin: Thank you, now it works: 马丁编辑:谢谢,现在可以使用:
function getMaxPos() {
var computetStyle = getComputedStyle(elm[0], null);
var tx, ty;
var transformOrigin =
computetStyle.transformOrigin ||
computetStyle.webkitTransformOrigin ||
computetStyle.MozTransformOrigin ||
computetStyle.msTransformOrigin ||
computetStyle.OTransformOrigin;
tx = Math.ceil(parseFloat(transformOrigin));
ty = Math.ceil(parseFloat(transformOrigin.split(" ")[1]));
return {
max: {
x: tx + window.innerWidth - elm.prop('offsetWidth'),
y: ty + window.innerHeight - elm.prop('offsetHeight')
},
min: {
x: tx,
y: ty
}
};
}
function mousemove($event) {
var x = startX + $event.clientX - initialMouseX;
var y = startY + $event.clientY - initialMouseY;
var limit = getMaxPos();
x = (x < limit.max.x) ? ((x > limit.min.x) ? x : limit.min.x) : limit.max.x;
y = (y < limit.max.y) ? ((y > limit.min.y) ? y : limit.min.y) : limit.max.y;
elm.css({
top: y + 'px',
left: x + 'px'
});
getMaxPos();
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.