这次给大家带来js怎样阻止图片拉伸自适应,js阻止图片拉伸自适应的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
相信大家在日常的web开发中,作为前端经常会遇到处理图片拉伸问题的情况。
例如banner、图文列表、头像等所有和用户或客户自主操作图片上传的地方,而一旦牵扯图片,就会涉及到图片拉伸的问题,当然,在图片上传时做手动裁切,让用户或客户清晰的感知到图片的有效内容才是最优的解决方案,但是在其他各种外在因素下,没有做裁切的话,就需要在前端显示上做处理了,满足在上传任意大小图片的情况下,最优显示效果的需求。
把图片放进框框,要几步?三步...我们开始
第一步:先画个框框 (这里顺便安利一种自适应框框的方法)
// 假定需要一个在750px屏幕下宽400px,高280px的盒子
// 宽度 = 400 / 750 = 0.5333
// 高度 = 280 / 400 * 0.5333 = 0.3733
<style>
.img-box{
position: relative;
width: 53.33%;
height: 0;
padding-bottom: 37.33%;
overflow: hidden;
background-color: #eee;
}
</style>
<body>
<p id="list">
<p class="img-box">
<img src="..."/>
</p>
</p>
</body>
第二步:设置图片需要使用到的css
<style>
.width{
position: absolute !important;
width: 100% !important;
min-height: 100% !important;
top: 50% !important;
transform: translatey(-50%) !important;
-ms-transform: translatey(-50%) !important;
-moz-transform: translatey(-50%) !important;
-webkit-transform: translatey(-50%) !important;
-o-transform: translatey(-50%) !important;
display: block;
}
.height{
position: absolute !important;
height: 100% !important;
min-width: 100% !important;
left: 50% !important;
transform: translatex(-50%) !important;
-ms-transform: translatex(-50%) !important;
-moz-transform: translatex(-50%) !important;
-webkit-transform: translatex(-50%) !important;
-o-transform: translatex(-50%) !important;
display: block;
}
</style>
第三步:js获取图片高度比较并给img添加类名
//需要注意的是,不能在css中直接给img设置宽度和高度
//否则在img.onload后获取的宽高是css设置的宽高
//同时建议使用dom对象来获取img标签
<script>
var list = document.getelementbyid('list');
getimgwh ( list );
//执行宽高比对并设置img类名
function getimgwh ( obj ) {
var img = obj.getelementsbytagname('img');
for( var i=0 ; i<img.length ; i++ ){
img[i].onload = function(){
var width = this.width;
var height = this.height;
if ( width > height ) {
this.classlist.add('height');
} else if ( width < height ) {
this.classlist.add('width');
} else {
this.style.width = '100%';
this.style.height = '100%';
}
}
}
}
</script>
图片防止拉伸处理比较简单,但是在实际项目中需要得到足够的重视,一个web页面成也图片,败也图片,拉伸了图片就等着设计师的磨叽吧,哈哈哈哈...
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jstree选中父节点时禁用子节点也被选中
swiper里自定义分页器使用步奏详解
以上就是js怎样阻止图片拉伸自适应的详细内容。