gpt4 book ai didi

javascript - css3旋转顶部和左侧坐标

转载 作者:行者123 更新时间:2023-11-28 04:57:41 25 4
gpt4 key购买 nike

我有 2 个 div - parent 和 child 。 child 是position:absolute

HTML:

<div id="parent">
<div id="child">
some text
</div>
</div>

CSS

#parent {position:relative; border:1px solid #000; width:200px; height:100px}
#child {position:absolute; top:0; left:0; background-color:maroon; opacity:0.5; width:150px; height:50px; border:1px solid #000}

我在 jsfiddle 中添加了更多元素以启用更改顶部和左侧坐标。
http://jsfiddle.net/zgvEC/1/

我面临的问题是——

  1. 当子 div 旋转 90 或 270 度时,元素不会定位到父 div 的左上角。子 div 的宽度/高度可以是任意的。如果子div的宽度可以容纳在父div的高度中,那么就不存在顶部和左侧位置的问题。我准备在这里做数学,但不知道要考虑什么。

  2. 当我拖动子div时,它的位置改变到右上角。

如果有任何帮助,请告诉我。非常感谢!!

最佳答案

首先你需要将旋转原点设置为左上角,然后旋转,

$("#child").css({
"-webkit-transform-origin": "top left",
"-moz-transform-origin": "top left",
"-o-transform-origin": "top left",
"transform-origin": "top left",
"transform" : "rotate("+ angle +"deg)"
});

这将围绕其(顶部、左侧)点旋转元素。

但是正如您在案例中所描述的,您需要 div 始终位于顶部,而您需要对 div 的边界进行一些数学运算。

您可以使用 document.getElementById(ele).getBoundingClientRect();

获取边界

然后你需要得到div旋转前后的边界。根据当前 Angular 应用数学逻辑。在此处查找代码以供引用。

$(function(){
$("#child").draggable();
var angle = 0;
$("#btn1").click(function(){
angle = angle + 90;
if(angle == 360) { angle = 0 }
// reset top left position to (0,0)
$("#child").css({"top": "0px", "left": "0px"});
var preBounds = getBounds("child");
$("#child").css({
"-webkit-transform-origin": "top left",
"-moz-transform-origin": "top left",
"-o-transform-origin": "top left",
"transform-origin": "top left",
"transform" : "rotate("+ angle +"deg)"
});
var currBounds = getBounds("child");

if(angle == 90)
{
$("#child").css({ "left": currBounds.left+Number(preBounds.left-currBounds.left)+"px"});
}
else if(angle == 180)
{
$("#child").css({ "top": currBounds.top+Number(preBounds.top-currBounds.top)+"px","left":currBounds.width+"px"});
}
else if(angle == 270)
{
$("#child").css({ "top": currBounds.height+"px"});
}
});


});

function getBounds(ele){
var bounds = document.getElementById(ele).getBoundingClientRect();
console.log(bounds);
//{left:bounds.left, top:bounds.top, right:bounds.right, bottom:bounds.bottom}
return bounds;
}

检查 fiddle一样的。希望对你有帮助

关于javascript - css3旋转顶部和左侧坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20137893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com