2014-04-05 225 views
0

這是我現在使用的代碼:設置圖像高度=寬度(不DIV)

(HTML)

<html> 
    <head> 
    <title>Float Image Gallery</title> 
    </head> 
    <body> 
    <button onclick="showAllGalleries();">Show gallery</button> 
    <div id="myGallery" class="gallery"> 
     <div class="gallery-close"> 
     <a href=#><img class="gallery-close-button" src="http://bit.do/closeicon" onclick="hideAllGalleries();" /></a> 
     </div> 
     <div class="gallery-content"> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /><br> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /><br> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /> 
     <img class="gallery-content-image" src="" alt="Please add image here" /><br> 
     </div> 
    </div> 
    </body> 
</html> 

(CSS)

.gallery { 
    display:none; 
    width:100%; 
    height:100%; 
    left:0; 
    bottom:0; 
    top:auto; 
    right:auto; 
    position:fixed; 
    background-color:#cccccc; 
    opacity:50%; 
} 

.gallery-close { 
    width:auto; 
    height:auto; 
    margin-top:10px; 
    margin-left:10px; 
} 

.gallery-close-button { 
    width:30px; 
    height:30px; 
} 

.gallery-content { 
    width:100%; 
    height:auto; 
    text-align:center; 
} 

.gallery-content-image { 
    width:20%; 
    height:20%; 
} 

.gallery-content-image:hover { 
    background-color:#ffffff; 
} 

(JS)

(這裏):
.gallery-content-image { 
    width:20%; 
    height:20%; 
} 

如果不編輯其他部分,我可以使高度與寬度相同嗎?
有沒有解決方案,不使用jQuery? (Javascript好吧)
任何幫助將不勝感激。

回答

0

百分比單位相對於您的瀏覽器窗口,因此您將獲得圖像寬度的20%的瀏覽器窗口寬度和圖像高度的20%的瀏覽器窗口高度。

因此,要使圖像爲正方形,應該指定像素(或其他單位)中的值相同。例如:width:100px;高度:100像素;

編輯

保持爲圖像的寬度的CSS,所以寬度:20%;

這裏的js代碼:

window.onresize = function() { 
      resize(); 
     }; 

     window.onload = function(){ 
      resize(); 
     };  

     function resize(){ 
      var imgs = document.getElementsByTagName('img'); 
      for(i = 0; i< imgs.length; i++){ 
       document.getElementsByTagName('img')[i].style.height = document.getElementsByTagName('img')[i].clientWidth; 
      } 
     } 
+0

所以,我怎麼能做到這一點在CSS得到它?我需要%,因爲我可以使用較小的窗口來顯示圖庫。 – Jamie

+0

檢查更新 – CMPS

0

你可以使用:

adsArray[i].setAttribute("hieght","40%"); 
adsArray[i].setAttribute("width","40%"); 
相關問題