如何在旋转后获得元素(DIV)的原始位置?

时间:2015-04-14 06:24:18

标签: javascript jquery html css css3

对于使用CSS变换旋转的DIV。

我需要在应用旋转之前获得DIV的原始位置(顶部,左侧,底部,右侧,宽度,高度)(以灰色div为例)。

http://jsfiddle.net/akycc4t1/7/

我知道我可以移除CSS轮播并使用Element.getBoundingClientRect(); 获得价值,但我想知道是否有更好的方法使用数学/几何。

我的需求是使用相对于视口左上角的坐标,以编程方式重新创建位于原始顶部之上的DIV。 其他方法或想法领域也欢迎。

<div id="example" style="display: none;"></div>
<div id="target" class="rotation"></div>
<div id="trace"></div>
<button id="btn-rotate" type="button">rotate</button>
<button id="btn-coordinate" type="button">get coordinate x,y</button>
<button id="btn-coordinate-notrotated" type="button">get coordinate as target was not rotated</button>

document.getElementById('btn-rotate').addEventListener('click', function (event) {
    document.getElementById('target').classList.add('rotation');
    document.getElementById('example').style.display = '';
}.bind(this));

document.getElementById('btn-coordinate').addEventListener('click', function (event) {
    alert(JSON.stringify(document.getElementById('target').getBoundingClientRect()));
}.bind(this));

document.getElementById('btn-coordinate').addEventListener('click', function (event) {
    alert(JSON.stringify(document.getElementById('target').getBoundingClientRect()));
}.bind(this));


document.getElementById('btn-coordinate-notrotated').addEventListener('click', function (event) {
    // solution here    
    alert('{top: xxxx,left: xxxx, right: xxxpx, width: 200, height: 200}');
}.bind(this));

#target {
    position:absolute;
    top:100px;
    left:100px;
    width:200px;
    height:200px;
    background-color: cyan;
    transform-origin: 50% 50% 0;
}
#trace {
    position:absolute;
    top:100px;
    left:100px;
    width:200px;
    height:200px;
    border: 1px solid darkgray;
    opacity: 0.1;
}
#example {
    position:absolute;
    top:100px;
    left:100px;
    width:5px;
    height:5px;
    background-color: red;
    z-index: 100;
}
.rotation {
    -ms-transform: rotate(10deg);
    -webkit-transform: rotate(10deg);
    transform: rotate(10deg);
}

2 个答案:

答案 0 :(得分:1)

使用.css(),尝试

document.getElementById('btn-coordinate-notrotated')
.addEventListener('click', function (event) {
     // solution here    
     var styles = $("#target")
                  .css(["height", "width", "top"
                      , "bottom", "left", "right"
                      , "background", "position"]);
    $("<div />", {"class":"clone", "css":styles}).appendTo("body");
    alert('{top: ' + styles.top + ',left: '
          + styles.left + ', right: ' 
          + styles.right + ', width: '
          + styles.width + ', height: '
          + styles.height + '}');
}.bind(this));

jsfiddle http://jsfiddle.net/akycc4t1/9/

答案 1 :(得分:0)

// solution here
var style = getComputedStyle(document.getElementById('target'));
alert('{top: ' + style.top + ', left: ' + style.left + ', width: 200, height: 200}');