appending images into center inside div using jquery
I am using crossSlide jquery plugin for my slideshow. My container is bigger than the images inside it so the tendency 开发者_运维问答of the images is positioned into left. Is there a way to position them centered to the container?
here's the sample site using crosSlide since i don't have a website to upload my sample page.
http://www.hashbangcode.com/blog/crossslide-jquery-plugin-test-348.html
Here's the jQuery to apply to your container after they're loaded in the ready function:
var xSlideWidth = $('#crossslide').width();
var xSlideHeight = $('#crossslide').height();
$('#crossslide').find('img').each(function(i,obj) {
var objXdiff = (xSlideWidth - $(obj).width())/2;
var objYdiff = (xSlideHeight - $(obj).height())/2;
$(obj).css({ 'left':objXdiff+'px', 'top':objYdiff+'px' });
});
Basically goes through each image contained within the #crossslide
and calculates how far to position the top
and left
(absolutely positioned relative to the #crossslide) according to how much smaller it is.
Determining the center of an element using jQuery:
if you know the innerWidth of the parent and the innerWidth of the element you can determine the left position you need to apply to achieve a "center".
$("#crossslide img").each(function() {
// let cl be (half parent width) - (half element width).
cl = ($(this).parent().innerWidth() / 2) - ($(this).innerWidth() / 2);
// we can set the left position to that value to achieve center
$(this).css("left", cl);
});
You would probably want to associate the function that performs this calculation with a handler for changing the size of the display port.
You might need to change the plugin to do this. I can be sure without seeing wht you are trying to accomplish. However, this works using absolute position of the images. However this seems to rely the container supplying the origin of the position - eg. the image is always at (0,0) of the container.
The plugin doesnt seem to have a way to allow you to change this in a simple fashion. However if you look at the options for the "Ken Burns Effect" it seems to have a way to do this. Whether its possible to configure a set of options that will produce the effect you want i dont know, but this would be my starting point.
I had the same issue, so I searched the jquery.cross-slide.min.js file for "left:" and found this section of code:
.css({position:"absolute",visibility:"hidden",top:0,left:14,border:0})
I edited the left position and it worked for me.
精彩评论