2011-04-18 74 views
2

我有一個包含幾個圖像的div。這些圖像風格出現在垂直列:從<img>到包含div的底部的距離(像素)

.side_gallery img { 
    display: block; 
    margin: 3px 5px; 
    padding: 0; 
    border: 1px solid #aaa; 
} 

我有一個JavaScript函數,它遍歷這些圖像和調整他們。我想要一個簡單的方法來計算從每個圖像的底部到包含<div>底部的距離(以像素爲單位)。

+0

你找到答案?如果是這樣,請接受一個。如果沒有,讓我們知道出了什麼問題,這樣我們可以提供幫助。 – Olical 2011-04-18 21:11:29

回答

2

您將需要獲取div(yourDiv.offsetHeight)的高度,圖像的位置(yourImage.offsetTop),圖像的高度(yourImage.offsetHeight),然後應用一點數學運算。

var div = document.getElementById('myDiv'); 
var image = document.getElementById('myImage'); 
var bottom = (div.offsetHeight) - (img.offsetTop + img.offsetHeight); 

Here is an example.

我希望這有助於。

+0

哦,等等,offsetTop使用頁面的頂部,讓我解決這個問題! – Olical 2011-04-18 12:53:53

+0

好的,修復它。只需要添加div的偏移高度。 – Olical 2011-04-18 13:02:34

+0

我認爲這會做到。我明天會測試它。 – TRiG 2011-04-18 22:24:42

0

如果你知道每個圖像的像素在div高度和位置,那麼你可以算一算,那麼你可以算一算:

如果圖像的位置是其左上角,那麼: Distance = DivSize - imageSize - imagePosition;

如果圖像的位置是它的左下角,然後: 距離= DivSize - imagePosition

我希望它能幫助:)

0

我覺得這是更好地使用jQuery的那些東西,因爲瀏覽器之間的差異

// this line launches our js after the page is loaded 
jQuery(document).ready(function() { 
// this line search for the images in the div with id = "content" 
    jQuery("#content >img").each(function(index) { 

    // caching img for saving time 
      var img =jQuery(this); 
    //get image height 
      var img_height = img.height() 
    //get image distance from parent top 
      var img_parent_top_distance = img.offset().top; 
    // get parent height 
      var parent_height=img.parent().height() 
    // do what you need width bottom distance (parent_height - img_parent_top_distance -img_height) 
      alert("img_height:"+img_height 
        +"\n img_parent_top_distance:"+img_parent_top_distance 
        +"\n parent_height:"+parent_height 
        +"\n bottom distance"+ (parent_height - img_parent_top_distance -img_height)) 
    }); 

});

作品與這個HTML

<h1>hola</h1> 
<div style="height:600px ;background-color: grey;" id="content"> 
<img src="gato1.jpg" id="1"> 
<img src="gato2.jpg" id="2"> 
<img src="gato3.jpg" id="3"> 
<img src="gato4.jpg" id="4"> 
<img src="gato1.jpg" id="1"> 
<img src="gato2.jpg" id="2"> 
<img src="gato3.jpg" id="3"> 
<img src="gato4.jpg" id="4"> 
</div>