开发者

Centering image gallery with jQuery, math calculation

Well, it's a bit confusing, but you can see here: http://www开发者_JAVA百科.stevenacres.com/meggriffiths/#bettydew

The images need to be centered. The captions also need to be flush left with the image, and the nav flush right. I couldn't use display:table-cell because I'm already using display:none to get the gallery to function properly, and since I have to use position:absolute and top:0 to get them to overlay, I can't really center them.

So I have the following two lines of jQuery:

$('.gallery ul li').each(function() {
    $('.gallery ul li').width($('.gallery ul li > img').width());
    $('.gallery ul li').css('margin-left','$(".gallery ul li > img").width() / 2');
});

The first one gets the width of each image and sets the li accordingly... that way, the caption and such can sit wherever the image sits. The second line is supposed to find the image's width, and set the css margin-left to the negative of this value, but I can't get the math calculation to work. What am I doing wrong?

This is the code that ended up working:

$('.gallery ul li').each(function() {
    $(this).width($(this).children().children().width() + 26);
    $(this).css('margin-left',-$(this).children().children().width() / 2 - 13);
});


i think problem is in this line of code....

$('.gallery ul li').css('margin-left','$(".gallery ul li > img").width() / 2')

width() returns value in pixels and you are doing arithmetic operation on it..so it will better if you parse it first and then do that calculation..

$('.gallery ul li').css('margin-left','parseInt($(".gallery ul li > img").width()) / 2')

i think this might be helpful to you...


You don't seem to be running the code in the correct spot. You are loading the gallery dynamically with jQuery's load. So the code should be inside the load's callback.

Furthermore, since your images might not be loaded at the time this code executes, you might not have the correct width() for the images, and your code probably won't work. You should really try to find a solution with css. Maybe with margin auto? Otherwise your code will have to be pretty complex to handle many of the edge cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜