[英]How can I rotate an element without covering the elements under it?
I have an application where my users might want to rotate the images they are shown to better view them. 我有一个应用程序,我的用户可能希望旋转显示的图像以更好地查看它们。
I figured I could just apply -moz-transform
and friends and be done with it, but then I realized that my browser does not seem to "push" elements out of the way like I expect, resulting in this: 我以为我可以应用
-moz-transform
和friends并完成它,但是后来我意识到我的浏览器似乎并没有像我期望的那样“推”元素,结果是:
My question is: is there a way for me to rotate the image, while having my browser move the elements around it in respect to its new dimensions? 我的问题是:在让浏览器相对于新尺寸移动元素的同时,是否可以旋转图像?
Here's a JSFiddle: http://jsfiddle.net/8pFUB/ . 这是一个JSFiddle: http : //jsfiddle.net/8pFUB/ 。 Click the image to rotate it and illustrate the problem.
单击图像以旋转它并说明问题。
In pure CSS, no. 在纯CSS中,没有。 But you can use jQuery to set some new margins:
但是您可以使用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
});
Fiddle: http://jsfiddle.net/8pFUB/21/ 小提琴: http : //jsfiddle.net/8pFUB/21/
Also to reply to Colonel Panic's answer, here is a version which sets all 4 margins: http://jsfiddle.net/8pFUB/24/ . 另外,为了回答Panic上校的回答,这是一个设置所有4个边距的版本: http : //jsfiddle.net/8pFUB/24/ 。 It's a bit less elegant in the rotation, so I'd suggest only setting the margins you actually want to change.
轮换的方式不太优雅,因此我建议仅设置您实际要更改的边距。
Full (adapted) code: 完整(自适应)代码:
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
})
}
Play with the margin values 玩保证金值
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'
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.