html中 img標簽顯示圖片中心的方法目前知道三種,在此記錄一下
第一種:用到css的clip:rect(top right bottom left);用法,需要配合position: absolute使用:如下
<img src="http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.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://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.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時候,顯示的圖片會出現(xiàn)一條灰色的邊框,而且沒有辦法去掉,border:0px也沒有作用,我之前的解決辦法是放一張默認的全透明的圖片在src中,就可以解決了。
第三種:在div中包含img,用div的overflow: hidden;來控制,用起來比較靈活,
<div style="width: 100px;height: 100px;overflow: hidden"> <img src="http://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.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://img2.utuku.china.com/640x0/news/20170210/77b8b5ca-11d3-4307-9a93-c12df5eb1a35.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){ img.width =100 ;//跟div高度一致 img.height = (100/realWidth)*realHeight;//等比縮放高度 img.style.top = '-' + ((100/realWidth)*realHeight-100)/2 + 'px';//設置圖片相對自己位置偏移為img標簽的高度-寬度的一半 }else { img.width =100 ; img.height = 100; } }; //圖片加載失敗的處理 img.onerror = function () { img.src = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1492076382452&di=04ebd6c4688b2ffbd8ae18e685234704&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fzhidao%2Fwh%253D450%252C600%2Fsign%3D0c96dc86da33c895a62b907fe4235fc6%2F0823dd54564e9258d2bb2dff9f82d158ccbf4e17.jpg"; img.width =100 ; img.height = 100; } </script>
上面注釋已經(jīng)很清楚了,主要是div控制了大小,img標簽根據(jù)div的大小來調(diào)節(jié)自身的大小。在進行偏移,從而達到顯示圖片中間部分的圖片。個人覺得第三種方法比較好用。
以上所述是小編給大家介紹的HTML中img標簽只顯示圖片中心位置的方法(三種方法),希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!