挨吻老湿分享了一坨圆角图像的另类实现方式文章 CSS3 Rounded Image With jQuery
很赞,翻译了下记录一把
开始之前,可以先把 Demo 点开对照着看
目标
目标是用 CSS3 border-radius 和 box-shadow 来实现如下图效果
左手: 圆角+外投影
你的右手旁边是我的左手: 圆角+内投影
问题
问题是这年头木有一档浏览器可以完美的在图片上应用圆角和阴影
webkit 可以显示圆角,但木有内投影
firefox 和内裤被戳破一样还坚挺的直着
CSS 淫技
灰常简单: 在图片外头套一层超薄<span />然后把原图作为 background-image.
要隐藏原图的话,可以 opacity:0 或 display:none
偶发现 opacity 更淫荡点,因为这么整用户还能图片另存为
当然出于某些阴暗目的或光明磊落隐私考虑,可能会偏向 display
最终用 jQuery 的解决方案
本着怎么偷懒怎么来的原则,我们用 jQuery 来自动给图片套<span />
不解释, 上代码先
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".rounded-img, .rounded-img2").load(function() {
$(this).wrap(function(){
return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
});
$(this).css("opacity","0");
});
});
</script>
接下来开始解释
1. 调用 jQuery 库
2. ready 就是 DOM 全部加载后再触发的事件, 否则一旦有图片的 DOM 节点后于 JS 加载,就会绑定不到
3. $(“.rounded-img, .rounded-img2″) 选中所有 class 名为 rounded-img 和 rounded-img2 的元素
4. 给俩元素集绑定 load 事件 (偶很疑惑为何这么写)
5. 在每个图片外面包含一个 span, 这个 span 的 class 为原元素的 class ,这个 span 的 style 里的 background 取值自原图的 src 值, 宽高同理
6. 给每个图片写个style=”opacity:0”
看起来素酱紫滴:
大猫的调整
$(function(){
$(".avatar").wrap(function(){
return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat center center; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
}).css("opacity","0");
});
理由:
1. $(document).ready(function(){}) 相当于 $().ready(function(){}) 相当于 $(function(){}) ,貌似有这么一说,嘻嘻
2. class名改为 .avatar 如果你是 wordpress 的评论头像, 都封装好了,要改结构也不是很方便,哈
3. 去掉图片的 .load 事件, 因为如果图片从缓存中获取, 有可能就不会触发这个事件, 反正是 DOM ready,霸王硬上弓了
4. 直接用链式写法点花点月点秋香
然后你得在你的主题 style.css 加上那么几条
因为 webkit 的内阴影配合圆角就是一坨屎,所以我用外阴影了
iPhone 的safari 还不支持 inset 内阴影, 如果有内阴影控, 可以用线性渐变配合RGBA假装是阴影…
.avatar {
display: inline-block;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, .4);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, .4);
box-shadow: 0 1px 3px rgba(0, 0, 0, .4);
background-image:none\9!important;
-moz-background-size:50px 50px;
-webkit-background-size:50px 50px;
background-size:50px 50px;
}
IE 呢?
screw you!
不过目前偶是弄个中间镂空PNG遮罩,多一个请求
要是平滑那还得PNG32
要是PNG32那IE6捏?
IE6用 AlphaImageLoader 滤镜一旦图片加载失败,整个页面就脱光了死给你看
screw IE!
Opera
这孩子长得漂亮,龙飞(dragonfly)也不错 就是没有用的欲望
10.x之后不用-o-了直接支持圆角阴影,值得鼓励
=====update===========================================
有bug了…如果图片是部分透明的IE下面的背景会透出来要写个hack
background-image:none\9!important;
加important的原因是路径是style写上去权重高,并且也不大可能后续越权的需求
background-size 这个属性也要写上,不然图片大小不一样很2的…
回复 Yang 取消回复