用 javascript 和 css 製作圖片截圖效果

圖片置中

做網站的時候,要做一個有很多圖片併排在一起的排版,因為每張圖片的長寬不一,所以排不好就很容易看起來不整齊,一個選擇是使用瀑布流的方式來排版,就像Pintrest的Pin。另一種則是可以讓圖片限制在一個比例內,如果超過的話就自動遮掉,像Pintrest的Board,剛好Pintrest都有做,拿來一起看就很清楚了。

要截圖很簡單,先用一個div把圖片給包起來,然後再設超過div的部分看不到就好了。
  1. <div class="img_wrap">  
  2.     <img src="img.jpg">  
  3. </div>  

css大概類似長這樣
  1. .img_wrap{   
  2.     width:72px;   
  3.     height:72px;   
  4.     overflow:hidden;   
  5.     position:relative;   
  6. }   
  7. img{   
  8.     position:absolute;   
  9. }  

設position的目的是圖片預設會對齊div的左上角,如果希望圖片自動對齊框框的中間,就要使用position去調整圖片的位置。

然後再用js根據圖片的長寬還有框框的長寬,選擇調整圖片的大小及位置,再加到inline CSS就完成了。

  1. function cropPhoto($width, $height, $wrapWidth, $wrapHeight){   
  2.     if(($width/$height) <= ($wrapWidth/$wrapHeight)){   
  3.         $picWidth=$wrapWidth;   
  4.         $picHeight=Math.round(($wrapWidth*$height)/$width);   
  5.         $shift=($wrapHeight-$picHeight)/2;   
  6.         $shift="top: "+$shift+"px";    
  7.     }else{   
  8.         $picHeight=$wrapHeight;   
  9.         $picWidth=Math.round(($wrapHeight*$width)/$height);   
  10.         $shift=($wrapWidth-$picWidth)/2;   
  11.         $shift="left: "+$shift+"px";   
  12.     }   
  13.     return {'picHeight': $picHeight, 'picWidth': $picWidth, 'getShift': $shift};   
  14. }  

留言

匿名表示…
請問一下 您是否有像是pinterest的pin一樣的排版教學?