我有一个应用程序,用户可能希望旋转显示的图像以更好地查看它们。
我想我可以申请-moz-transform
和朋友一起完成它,但后来我意识到我的浏览器似乎没有像我期望的那样“推”元素,导致这个: / p>
我的问题是:有没有办法让我旋转图像,同时让浏览器根据新尺寸移动元素?
这是一个JSFiddle:http://jsfiddle.net/8pFUB/。单击图像以旋转它并说明问题。
答案 0 :(得分: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/
同样回复Panic上校的答案,这里有一个设置所有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
})
}
答案 1 :(得分: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'
});