我有一个div,其中包含一些图像。这些图像的样式显示在垂直列中:
.side_gallery img {
display: block;
margin: 3px 5px;
padding: 0;
border: 1px solid #aaa;
}
我有一个javascript函数在这些图像上循环并调整它们。我想要一种简单的方法来计算从每个图像的底部到包含<div>
的底部的距离(以像素为单位)。
您将需要获得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);
下面是一个例子。
如果你知道每个图像的高度(以像素为单位)以及它在div中的位置,那么你可以进行计算,然后你可以进行计算:
如果图像的位置在左上角,则:
距离= DivSize - imageSize - imagePosition;如果图像的位置在左下角,则:距离= DivSize - imagePosition
我希望这对你有帮助。
由于浏览器之间的差异,我认为使用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>