无论图像大小或宽高比如何,总是将图像放在div的中心有一个很好的CSS技巧。
<style>
.img_wrap {
padding-bottom: 56.25%;
width: 100%;
position: relative;
overflow: hidden;
}
#imgpreview {
display: block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
<div class="img_wrap">
<img id="imgpreview" src="http://i.imgur.com/RRUe0Mo.png" alt="your image" />
</div>
然后我添加了用于旋转图像的jquery代码
$(document).ready(function(){
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
};
$('#imgpreview').click(function() {
rotation += 90;
$(this).rotate(rotation);
// $(this).toggleClass("imgpreview");
});
});
然而,当我是旋转图像时,它会被裁剪。我想避免这种情况。
我尝试使用addClass功能,但没有成功。如果有人可以建议任何解决方案会很感激。
答案 0 :(得分:1)
你可以通过改变你的代码来实现jquery:
$('#imgpreview').click(function() {
if (rotation === 360) {
rotation = 0
} else {
rotation += 90;
}
$(this).rotate(rotation);
if(rotation === 90 || rotation === 270) {
$('.img_wrap').css('height', $(this).width());
} else {
$('.img_wrap').css('height', 'auto');
}
});
也许还需要改变你的CSS,但这取决于你希望得到的最终结果。
答案 1 :(得分:1)
有很多方法可以做到这一点
下面的jQuery确定它是否是垂直的。
您只需将此行添加到您的函数(度)中
((degrees/90) == 1 || (degrees/90) == 3)? $(this).css('width','56.25%'):$(this).css('width','auto');
答案 2 :(得分:1)
所以这就是我对你的代码所做的:
删除overflow: hidden
的{{1}}。
在JS中我这样做了:
img_wrap
请注意, $('.imgpreview').click(function() {
rotation += 90;
rotation %= 360;
$(this).rotate(rotation);
// when rotation is 90 or 270
if ((rotation / 90) & 1) {
$(this).css({
'width': $('.img_wrap').innerHeight(),
'max-height': $('.img_wrap').innerWidth()
});
} else {
$(this).css({
'width': 'auto',
'max-height': '100%'
});
}
});
/ width
计算是在调用height
函数后完成的。 轮换后,rotate
为width
,反之亦然height
,因此我们必须在设置imgpreview
height
时调整width
{1}} - 因此imgpreview
样式调整。
见下面的演示:
max-height
$(document).ready(function() {
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({
'-webkit-transform': 'rotate(' + degrees + 'deg)',
'-moz-transform': 'rotate(' + degrees + 'deg)',
'-ms-transform': 'rotate(' + degrees + 'deg)',
'transform': 'rotate(' + degrees + 'deg)'
});
};
$('.imgpreview').click(function() {
rotation += 90;
rotation %= 360;
$(this).rotate(rotation);
// when rotation is 90 or 270
if ((rotation / 90) & 1) {
$(this).css({
'width': $('.img_wrap').innerHeight(),
'max-height': $('.img_wrap').innerWidth()
});
} else {
$(this).css({
'width': 'auto',
'max-height': '100%'
});
}
});
});
body {
margin: 0;
}
.img_wrap {
width: 100%;
position: relative;
border: 3px solid black;
padding-bottom: 56.25%;
/*overflow: hidden;*/
}
.imgpreview {
display: block;
max-height: 100%;
max-width: 100%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}