Emulating CSS3 background-size with jQuery
I have a circular image carousel that pretty much covers the whole of the browser viewport. Each carousel item is an image that needs to be rendered in the style of CSS3's background-size: cover
for landscape images, and background-size: contain
for portrait images. Of course, for browsers that support it, that's what I use and it works fine.
I'm trying to implement a jQuery-based fallback for browsers that don't support these CSS3 properties.
if (Modernizr.backgroundsize) {
// all good, do nothing (except some housekeeping)
}
else {
// emulate background-size:cover
$('.slide img').each(function() {
iw = $(this).width();
ih = $(this).height();
开发者_如何学Go iratio = iw/ih;
if (iw >= ih) { // landscape
var newHeight = w / iratio;
if (ih<h) {
$(this).css({height:newHeight, width:w}); // fix this
// use negative margin-left to show center?
} else {
$(this).css({height:newHeight, width:w});
// set negative margin-top to show the center of the image
}
} else { // portrait
var newWidth = h * iratio;
$(this).css({height:h, width:newWidth});
}
});
精彩评论