Changing margin of a div with javascript
I'm making a webpage that contains a picture gallery. I've written a javascript function to display a larger version of an image when you click on the miniature. What the function does is that it changes the search path of an img tag within a div that is hidden. It then changes the top and left values of the div to position the div in the center of the screen and then it's supposed to adjust the top and left margin of the div depending on the image size to place its middle in the center of the screen.
This is where it fails. Or really, it works, but not when it's supposed to. If I open an image for the first 开发者_运维知识库time it has the wrong offset from the center (the negative margins for top and left are wrong). If I open it again however, it works! I get the same error if I open an image with a different width and height.
This is the code used to set the margins:
imagebox.style.marginLeft=(image.width/-2)+'px';
imagebox.style.marginTop=(image.height/-2)+'px';
This works just fine in google chrome and and in safari, but in other browsers it doesn't always use this code and sometimes it gives it a double call.
And in the end I of course set the div visibility to visible.
Try the jQuery functions .css()
and .width()
/.height()
. They work fine in almost every browser.
精彩评论