2013-08-05 55 views
2

我有一个应用程序,我的用户可能想旋转它们显示的图像以更好地查看它们。如何旋转元素而不覆盖下面的元素?

我想我可以只申请-moz-transform和朋友,用它做的,但后来我意识到,我的浏览器似乎没有了像我期望的那样“推”的元素,造成这样的:

oops

我的问题是:有没有一种方法可以让我旋转图像,同时让我的浏览器围绕它的新维度移动元素?

这是一个JSFiddle:http://jsfiddle.net/8pFUB/。点击图片旋转并说明问题。

回答

3

在纯CSS中,没有。但是你可以使用jQuery来设置一些新的边距:

var e = $(el); 
e.css({ 
    'margin-bottom': (e.width() * Math.abs(Math.sin(degree * Math.PI/180.0)) + e.height() * (Math.abs(Math.cos(degree * Math.PI/180.0)) - 1))/2 
}); 

小提琴:http://jsfiddle.net/8pFUB/21/

而且回复上校恐慌的答案,这里是将所有4利润率版本:http://jsfiddle.net/8pFUB/24/。这在旋转中稍显优雅,所以我建议只设置你实际想改变的边距。

满(改编)代码:

function setPaddedRotation(element, degree) { 
    var e = $(element); 
    var rads = degree * Math.PI/180.0; 
    var ss = Math.abs(Math.sin(rads)); 
    var cc = Math.abs(Math.cos(rads)); 
    var padx = (e.height() * ss + e.width() * (cc - 1))/2; 
    var pady = (e.width() * ss + e.height() * (cc - 1))/2; 
    e.css({ 
     '-webkit-transform': 'rotate(' + degree + 'deg)', 
     '-moz-transform': 'rotate(' + degree + 'deg)', 
     '-ms-transform': 'rotate(' + degree + 'deg)', 
     '-o-transform': 'rotate(' + degree + 'deg)', 
     'transform': 'rotate(' + degree + 'deg)', 

     // remove any of these which you don't want 
     'margin-top': pady, 
     'margin-bottom': pady, 
     'margin-left': padx, 
     'margin-right': padx 
    }) 
} 
+0

我喜欢这种方法,但它仍然有问题:HTTP:/ /jsfiddle.net/8pFUB/22/ –

+0

@ColonelPanic在这种情况下,也只是给予margin-top以相同的值。如果需要,也可以使用相同的逻辑来设置左右页边距。 – Dave

+0

你是@Dave!它效果很好。 –

1

播放与保证金

function degToRad(deg) { 
    return Math.PI * deg/180; 
} 
var height = img.height, 
    width = img.width, 
    rad = degToRad(deg), 
    sin = Math.abs(Math.sin(rad)), 
    cos = Math.abs(Math.cos(rad)), 
    dh = cos * height + sin * width - height, 
    dw = cos * width + sin * height - width; 
$(img).css({ 
    'margin-top': dh/2 + 'px', 
    'margin-bottom': dh/2 + 'px', 
    'margin-left': dw/2 + 'px', 
    'margin-right': dw/2 + 'px' 
}); 

DEMO