头像“截取”,图片使用居中显示,在头像跟上传中应该用的到

喜欢的朋友可以自己去下载一下。 https://pan.baidu.com/s/1eS1B50e 点击下载

PS:无论图片怎么样,外面设置一个div,图片能始终以图片自身的中心位置开始显示在div中间  对于做头像很有用,喜欢的朋友可以看看,菜鸟一个,不好的地方请留言指出

 HTML中

<div class="pictures">
<img src="18.jpg" alt=""/>
</div>

<div class="pictures">
<img src="5.jpg" alt=""/>
</div>
<div class="pictures">
<img src="13.jpg" alt=""/>
</div>
<div class="pictures">
<img src="24.jpg" alt=""/>
</div>
<script src="jquery1.9.0.js"></script>
<script src="demo.js"></script>


引入了JQ的框架 所以在使用的时候需要引入JQ(1.9以上)
demo.js文件中代码如下:
function middleP(className, width, height) {
$("." + className).css({
"width": width,
"height": height,
"overflow": "hidden",
"position": "relative"
})
var imgArr = $("." + className).find("img");
var x,y;
for (var i = 0; i < imgArr.length; i++) {
imgSize($(imgArr[i]), width, height);
//imgMargin($(imgArr[i]),width,height);
(function (imgArr,width,height) {
x = ( imgArr.width() - width) / 2;
y = ( imgArr.height() - height) / 2;
$(imgArr.css({
"margin-left": -x,
"margin-top": -y
}))
})($(imgArr[i]),width,height);

}
};
function imgSize(img, width, height) {
if (img.width() >= img.height()) {
if(height>=width){
img.css({
"height": height,
"width": "auto"
})
}else{
img.css({
"height": "auto",
"width":width
})
}

} else {
if(height>=width){
img.css({
"height": "auto",
"width": width
})
}else{
img.css({
"width": "auto",
"height": height
})
}


}
}

$(window).load(function(){
middleP("pictures",100,100);//参数1:类名 参数2:显示的宽度 参数3:显示的高度
})
posted @ 2016-08-29 19:13  小前端学习  阅读(1075)  评论(0编辑  收藏  举报