Display random image with varying dimensions using jquery
I have a simple page that loads a random image from an array and positions it centrally using negative margins in CSS. This currently works as all the images are the same size, but I would like to adapt the code so that it can accommodate images with varying dimensions.
Is it possible to calculate the height and width of an image at the array stage, then pass it through to the CSS/HTML to position it centrally? Here is the code I am currently working with – any help would be greatly appreciated.
HTML/CSS:
#content {
margin-top: -206px;
margin-left: -290px;
position: absolute;
top: 50%;
left: 50%;
width: auto;
height: auto;
}
<div id="content">
<img class="shuffle" src="" width="580" height="413" border="0" alt="" />
</div>
JQuery:
$(document).ready(function() { $('.shuffle').randomImage({path: 'images/'}); } );
(function($){ $.randomImage = { defaults: { path: 'images/', myImages: [ 'image01.jpg', 'image02.jpg','image03.jpg', 'image04.jpg', 'image05.jpg' ] } }
$.fn.extend({ randomImage:function(config) {
var config = $.extend({}, $.randomImage.defaults, config);
return this.each(function() {
va开发者_运维问答r imageNames = config.myImages;
var imageNamesSize = imageNames.length;
var randomNumber = Math.floor(Math.random()*imageNamesSize);
var selectedImage = imageNames[randomNumber];
var fullPath = config.path + selectedImage;
$(this).attr( { src: fullPath, alt: selectedImage } );
});
}
});
})(jQuery);
This way:
...
var fullPath = config.path + selectedImage;
var img = new Image();
img.src = fullPath;
var width = img.width;
alert(width);
...
I tested it in FF3.6 and it works.
Hope this helps. Cheers
Thank you; that pointed me in the right direction. Below is the code I ended up with, which works in Firefox 5 and Safari 5. It is not particulary elegant, but is functional – perhaps someone else might be able to simplify it.
Edit 19.07.11: Based on the example here I have simplified the code considerably; however I feel it could do with further work to simplify it further.
html:
<div id="wrapper">
<div id="content"></div>
</div>
jquery:
jQuery(document).ready(function($) {
var images = ['image01.jpg', 'image02.jpg','image03.jpg','image04.jpg','image05.jpg'];
$('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#content');
(function($) {
$.fn.verticalAlign = function() {
return this.each(function(i) {
var oh = $(this).height();
var wh = $(window).height();
var middle = (wh - oh) / 2;
if (middle > 0) {
$(this).css('margin-top', middle);
} else {
$(this).css('margin-top', 0);
}
});
};
})(jQuery);
$(window).load(function() {
$("#content").verticalAlign();
var showContent = function() { $('#content').fadeIn(750); };
setTimeout(showContent, 100);
});
$(window).bind('resize', function() {
$("#content").verticalAlign();
});
});
精彩评论