img及父元素(容器)实现类似css3中的background-size:contain / background-size:cover
2015-10-08 15:38
555 查看
img及父元素(容器)实现类似css3中的background-size:contain / background-size:cover
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <style> .item{ width:600px; height:500px; float:left; background-color:black; } body:after{ content:""; display:block; clear:both; } </style> </head> <body> <div class="item"><img src="img/720x480.jpg" /></div> <div class="item"><img src="img/snack.jpg" /></div> <script type="text/javascript" src="js/jquery.js"></script> <script> $(function () { /* 定义jQuery插件 imageSize 使用方式 $("容器").imageSize("contain") 或 $("容器").imageSize("cover") */ $.fn.imageSize = function (type) { this.each(function () { var This = $(this), $img = This.find(">img"), box_width = This.width(), box_height = This.height(); getRealImageSize($img.attr("src"), function (w, h) { if (type == "contain") {//跟background-size:contain一样效果 if (box_width / box_height <= w / h) { $img.css({ width: "100%", height: "auto", paddingTop: ((box_height - box_width * h / w) / 2) + "px" }); } else { $img.css({ height: "100%", width: "auto", paddingLeft: ((box_width - box_height * w / h) / 2) + "px" }); } } else if (type == "cover") {//跟background-size:cover一样效果 This.css("overflow", "hidden"); if (box_width / box_height <= w / h) { $img.css({ width: "auto", height: "100%" }); } else { $img.css({ height: "auto", width: "100%" }); } } else {//无效果 This.css("overflow", "hidden"); } }); }); //引用自http://www.zhihu.com/question/28733200 function getRealImageSize(url, callback) { var img = new Image(); img.src = url; // 如果图片被缓存,则直接返回缓存数据 if (img.complete) { callback(img.width, img.height); } else { // 完全加载完毕的事件 img.onload = function () { callback(img.width, img.height); } } } }; /* 开始调用插件 */ $(".item").imageSize("contain"); }); </script> </body> </html>
相关文章推荐
- 【笔记】利用CSS3特性实现圆角DIV
- css透明度
- css外部与内部样式表
- css position: relative | absolute | static | fixed详解
- 转载 -- CSS3 中关于 select 下拉列表的样式
- 一览css布局标准
- <input type="file">定义样式并获取上传文件路径及指定文件类型
- <input type="file">定义样式并获取上传文件路径及指定文件类型
- 【Qt】QTableView表格滚动条样式实现QStyleSheet
- css中width:auto和width:100%的区别有哪些
- CSS3弹性盒模型flexbox完整版教程
- Dialog使用自定义的样式
- css布局模型之绝对定位与相对定位
- JS+CSS实现的蓝色table选项卡效果
- JS+CSS实现的蓝色table选项卡效果
- css关于浮动的例子--float
- 用CSS来画圆
- Holder 可直接在客户端渲染图片的占位。支持在线和离线,提供一个链式 API 对图像占位进行样式处理。
- CSS 盒模型
- css选择器优先级