Distance (pixels) from an <img> to the bottom of the containing div
I have a div which contains a few images. The images are styled to appear in a vertical column:
.side_gallery img {
display: block;
margin: 3px 5px;
padding: 0;
border: 1px solid #aaa;
}
I have a javascript function which loops over these images and tweaks them. I want a si开发者_如何学运维mple way to calculate the distance, in pixels, from the bottom of each image to the bottom of the containing <div>
.
You are going to need to get the height of the div (yourDiv.offsetHeight
), the location of your image (yourImage.offsetTop
), the height of your image (yourImage.offsetHeight
) and then apply a tiny bit of math.
var div = document.getElementById('myDiv');
var image = document.getElementById('myImage');
var bottom = (div.offsetHeight) - (img.offsetTop + img.offsetHeight);
Here is an example.
I hope this has helped.
If you know the height of each image in pixels and its position in the div then you can do the math, then you can do the math:
If the position of the image is its top left corner, then: Distance = DivSize - imageSize - imagePosition;
If the position of the image is its bottom left corner, then: Distance = DivSize - imagePosition
I hope it helps :)
I think it is better to use jQuery for those things because of differences between browsers
// 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) )
});
});
works with this 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>
精彩评论