屏幕中间有一个宽高未知的图片,点击旋转或放大按钮时,如何让图片始终在屏幕中间?
ps:代码如下,为什么还是不能居中,这有什么问题么?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style>
*{padding:0; margin:0;}
html,body{height:100%; position: relative;}
img{border:0; vertical-align: middle;}
#box{ position:absolute;}
</style>
<script src="js/jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
var width ='',
height = '',
src='images/123.jpg';
$('#boxImg').attr('src',src);
var img = new Image();
img.src = src;
img.onload = function(){
width = img.width;
height = img.height;
};
$('#box').css({
'width':width+'px',
'height':height+'px',
'marginLeft':-width/2+'px',
'marginTop':-height/2+'px',
'top':50+'%',
'left':50+'%'
});
});
</script>
</head>
<body>
<div id="box">
<img id="boxImg" src="" alt="">
</div>
</body>
</html>
css3 translate配合position absolute
动画,矩阵变换…改变中心点
以前postion:absolute + 50% + 负margin的方式一样适用
只不过有css3可以把负margin改为translate(-50%,-50%)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title></title>
<style>
body,html{
height:100%;
}
#test{
position:absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
#myimg{
background-color:#f00;
transform: scale(1.5);
}
</style>
</head>
<body>
<div id="test">
<div style="width:300px;height:200px" id="myimg">
</div>
</body>
</html>