html中 img标签显示图片中心的方法目前知道三种,在此记录一下
第一种:用到css的clip:rect(top right bottom left);用法,需要配合position: absolute使用:如下
<img src="http://huoche.7234.cn/images/jb51/yjcqhaah4sh.jpg"
style="position: absolute;clip: rect(0px,250px,200px,50px);width: 300px;height: 200px">设置图片的width和height相当于图片实际宽高的等比例缩放,再用rect方法来设置图片的剪切范围。
– 第二种:用img的background属性:
<style type="text/css">
img {
background-image: url(http://huoche.7234.cn/images/jb51/yjcqhaah4sh.jpg);//设置背景图片
background-repeat: no-repeat;//背景图像将仅显示一次。
background-attachment: scroll;//
background-position: -50px 0px;//设置背景图片的的偏移量,这个-50相当于背景整体向左偏移50,就可以显示图片的中心
background-size: 300px 200px;////设置背景图片的大小,相当于图片实际宽高等比例饿缩放的
background-color: transparent;//
width: 200px;//
height: 200px;//
}
</style>用背景来控制图片显示中心位置,需要设置背景按照图片的真实宽高等比缩放,然后偏移背景的移动量来控制图片的宽高,这个需要注意的是不能图片的src,img标签不设置src时候,显示的图片会出现一条灰色的边框,而且没有办法去掉,border:0px也没有作用,我之前的解决办法是放一张默认的全透明的图片在src中,就可以解决了。
第三种:在div中包含img,用div的overflow: hidden;来控制,用起来比较灵活,
<div style="width: 100px;height: 100px;overflow: hidden">
<img src="http://huoche.7234.cn/images/jb51/yjcqhaah4sh.jpg" style="position: relative" id="img_id">
</div>
<script>
var img = document.getElementById("img_id");
var image = new Image();
var realWidth = 0;//储存图片实际宽度
var realHeight = 0;//储存图片实际高度
//获取图片的宽高
image.src = "http://huoche.7234.cn/images/jb51/yjcqhaah4sh.jpg";
//加载成功的处理
image.onload = function () {
realWidth = image.width;//获取图片实际宽度
realHeight = image.height;//获取图片实际高度
//让img的宽高相当于图片实际宽高的等比缩放,然后再偏移
if (realWidth > realHeight){
img.width = (100/realHeight)*realWidth;//等比缩放宽度
img.height = 100;//跟div高度一致
img.style.left = '-' + ((100/realHeight)*realWidth-100)/2 + 'px';//设置图片相对自己位置偏移为img标签的宽度-高度的一半
}else if (realWidth < realHeight){









