HTML5/jQuery Cross-Browser Responsive Images
I'm trying to devise a method of displaying images that resize responsively in a cross-browser-compatible manner. Using CSS3 media queries won't do because they're not supported widely. jQuery, however, affords me the ability to utilize the "data" attributes in HTML5.
This is what I have come up with. Does anyone else have good ideas? Or can offer any tweaking on this idea?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5/jQuery Responsive Images</title>
<style>
body { padding: 0; margin: 0; }
</style>
开发者_如何学Python <script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script>
$(window).resize(setSize)
$(document).ready(setSize);
function setSize() {
var bodywidth = $(document).width();
var small_max = 600;
var medium_max = 800;
if (bodywidth > small_max && bodywidth <= medium_max) {
$('img').each(function(){
$(this).attr('src',$(this).data('src-800px'));
});
} else if (bodywidth <= small_max ) {
$('img').each(function(){
$(this).attr('src',$(this).data('src-600px'));
});
} else if (bodywidth > medium_max ) {
$('img').each(function(){
$(this).attr('src',$(this).data('src'));
});
}
}
</script>
</head>
<body>
<img data-src="image.jpg" data-src-600px="image-600px.jpg" data-src-800px="image-800px.jpg" alt="Responsive image" style="width: 100%;" />
</body>
</html>
Setting the img tag to display:inline would handle the responsiveness for you.
Have a look at a series of blog posts I did on this:
http://queryj.wordpress.com/2012/07/06/responsive-images-whats-the-problem-9-2/
Basically:
- Place image tag in a block
- Progressively enhance the page by adding an image based on the noscript block
- Use media query listener to change the image when required
You need a couple of polyfills for this technique - one to be able to read the noscript tag textContent property and one to provide media queries and media query listeners to IE < 10.
精彩评论