jQuery .position() strangeness while using CSS3 rotate attribute

前端 未结 2 1328
再見小時候
再見小時候 2021-01-08 00:12

I\'m getting absolutely positioned rotated elements position with jQuery .position() method, then setting position-related attributes (top, left) with jQuery

2条回答
  •  悲哀的现实
    2021-01-08 00:35

    // Needed to read the "real" position
    $.fn.adjustedPosition = function() {
        var p = $(this).position();
        return {
            left: p.left - this.data('dx'),
            top: p.top - this.data('dy')
        }
    };
    

    $(function() { 
    
        var img = $('img'),
            pos;
    
        // Calculate the delta
        img.each(function() {
            var po = $(this).position(), // original position
                pr = $(this).addClass('rot').position(); // rotated position
    
            $(this).data({
                dx: pr.left - po.left, // delta X
                dy: pr.top - po.top // delta Y
            });
        });
    
        // Read the position
        pos = img.adjustedPosition();    
        alert(pos.left + '/' + pos.top);     
    
        // Write the position
        img.css(pos);
    
        // Read the position again
        pos = img.adjustedPosition();    
        alert(pos.left + '/' + pos.top);
    
    });
    

    Live demo: http://jsfiddle.net/2gVL4/4/

    So what is going on here:

    1. The CSS code that rotates the image is stored inside a special CSS class. I do this because I want to read the original position of the image (before rotating). Once I read that original position, I apply the .rot class, and then read the position again to calculate the difference (delta), which is stored inside the element's data().

    2. Now, I can read the position via the custom method adjustedPosition (which is defined above). This method will read the position of the element and then subtract the delta values stored inside the data() of the element.

    3. To write the position, just use the css(pos) method like normally.

提交回复
热议问题