我会建议使用CSS方法。定义HTML作为 -
<img class="user-profile-avatar" src="">
,然后你可以在CSS定义头像图片 -
.user-profile-avatar{
background: url('YOUR_DEFAULT_AVATAR_IMAGE_URL') no-repeat 0 0 transparent;
// additionally you can add height width to image for better results
height: 300px;
width: 240px;
}
这样,你不需要在HTML载入多张图片(甚至不是从cache),它可能发生如果您使用<img src-"some_source">
,并且一旦DOM正在构建并且页面开始呈现,您将能够看到默认的头像图像。
在页面加载后,您可以通过JS设置用户图像。
或
使用以下方式
HTML代码 -
<div class="user-profile-avatar" data-profile-src="YOUR_USER_IMAGE_URL"></div>
CSS -
.user-profile-avatar{
background: url('YOUR_DEFAULT_AVATAR_IMAGE_URL') no-repeat 0 0 transparent;
// additionally you can add height width to image for better results
height: 100px;
width: 80px;
}
JS -
$(function(){
$(".user-profile-avatar").each(function(){
var el = $(this);
var src = el.data("profile-src") != "" ? el.attr("data-profile-src") : "http://www.newportoak.com/wp-content/uploads/default-avatar.jpg";
el.css({
"background-image": "url('"+src+"')"
});
});
});
我使用jQuery来简化演示。 http://jsfiddle.net/Pu9NU/
你不能简单地在html本身设置一个默认图像吗? ''?你可以覆盖它,一旦你得到用户指定图像的来源。 –
A [dup](http://stackoverflow.com/questions/24254480/how-to-prevent-none-images-to-be-seen-in-browsing-using-jquery),并附上您接受的答案? – Teemu