【发布时间】:2012-02-19 02:24:05
【问题描述】:
作为一个简单的解释,我创建了一个使用此功能调整大小以填充背景的图像,效果很好:
function resize_bg(element_id){
$("#"+element_id).css("left","0");
var doc_width = $(window).width();
var doc_height = $(window).height();
var image_width = $("#"+element_id).width();
var image_height = $("#"+element_id).height();
var image_ratio = image_width/image_height;
var new_width = doc_width;
var new_height = Math.round(new_width/image_ratio);
if(new_height<doc_height){
new_height = doc_height;
new_width = Math.round(new_height*image_ratio);
var width_offset = Math.round((new_width-doc_width)/2);
$("#"+element_id).css("left","-"+width_offset+"px");
}
$("#"+element_id).width(new_width);
$("#"+element_id).height(new_height);
return true;
}
所以完整的背景图片没有问题。当我使用 Javascript 更改图像源时,问题出现了。换句话说,我将 1 张图像设置为背景,但在页面上某些元素悬停时,图像会发生变化,但不会改变调整大小。因此,加载的第一张图片已正确调整大小和定位,但是当我使用 .attr('src',newimg) 切换图片时,即使我再次调用该函数,图片也未正确调整大小。
这是我用来更改图像和调整大小的代码:
$('#menu_work li a').hover(function(){
$('#content').hide();
var img_src = $(this).next('img').attr('src');
$('#full_screen_img').attr('src', img_src );
resize_bg();
$('#full_screen_img').show();
},function(){
$('#full_screen_img').hide();
$('#content').show();
});
感谢您的帮助。
【问题讨论】:
-
你能显示你调用
resize_bg函数的代码吗?在加载和元素悬停时。 -
@micha - 是的,我有,请查看问题中添加的代码。
-
您确认
img_src的值是您期望的值吗?
标签: javascript jquery