I am trying to duplicate the way Google displays background image on its main page. Basically here is my code rewrite of it:
<img style="width: 1279px; height: auto; left: 0px; opacity: 0.99999;" src="<?php echo $_COOKIE['otakuplus_bg']; ?>" id="cpBackgroundImg">
The problem with this is if you look into Googles homepage they actually get the image's dimensions, so in this case, my width is 1279px while height is auto.
This is because I entered the with int开发者_StackOverflow中文版o CSS manually. However, google seems to get the exect same data in a different manner; probably via JS.
So, their data would be:
width: 1279px; height: 959.25px;
...for the same image. I have to rely on auto for the height. If you know of a way I can do this with jQuery, please tell me. Thank you in advance.
Using JQuery:
width of that element
var imgWidth = $("#cpBackgroundImg").width();
alert(imgWidth);
height of that element
var imgHeight = $("#cpBackgroundImg").height();
alert(imgHeight);
Now you should hopefully have the width and height stored in JQuery, you can do what you want with it. http://jsfiddle.net/robx/BHyLJ/
here's how i am outputting a prepared picture that fits the user's window just right.
Steps:
get the window's width & height and store it in
container_height and container_width
use jQuery and TimThumb PHP library. TimThumb can generate resized images on the fly while zoom-cropping the parts that won't fit the given size.
$('#container').css('background','url(timthumb.php?src=image_source.jpg&w=' + container_width + '&h=' + container_height + '&zc=1');
What it does is just to change the css background property of the element with the id="container" to the image generated by timthumb.
You can get TimThumb here: http://code.google.com/p/timthumb/
good luck
btw. in my code i also add a preloader to make sure the background becomes visible when it's fully loaded.
You can't know the height and width of the image until it loads. So say your image is like this:
<img src="foo.jpg" id="foo">
You can do this in jQuery:
var img = jQuery("#foo");
if (img.attr("complete")) {
// Comes from the cache so no load event will fire
alert("width = " + img.width());
} else {
img.load(function() {
alert("width = " + img.width());
}
}
精彩评论