今天就跟大家聊聊有關(guān)Javascript中怎么防止圖片拉伸,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供保定企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、H5技術(shù)、小程序制作等業(yè)務(wù)。10年已為保定眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站制作公司優(yōu)惠進(jìn)行中。
第一步:先畫個(gè)框框 (這里順便安利一種自適應(yīng)框框的方法)
// 假定需要一個(gè)在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>
<div id="list">
<div class="img-box">
<img src="..."/>
</div>
</div>
</body>
第二步:設(shè)置圖片需要使用到的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設(shè)置寬度和高度
//否則在img.onload后獲取的寬高是css設(shè)置的寬高
//同時(shí)建議使用dom對(duì)象來獲取img標(biāo)簽
<script>
var list = document.getElementById('list');
getImgWH ( list );
//執(zhí)行寬高比對(duì)并設(shè)置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>
看完上述內(nèi)容,你們對(duì)Javascript中怎么防止圖片拉伸有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。
當(dāng)前標(biāo)題:Javascript中怎么防止圖片拉伸
路徑分享:http://aaarwkj.com/article24/iihgje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供自適應(yīng)網(wǎng)站、品牌網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、動(dòng)態(tài)網(wǎng)站、搜索引擎優(yōu)化、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)