作为一个快速解释,我创建了一个图像,使用这个功能调整大小以填充背景,效果很好:
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();
});
感谢您的帮助。
最佳答案
在 hover
事件处理程序中调用 resize_bg()
时,您似乎遗漏了 element_id
参数。因此,resize_bg()
找不到您要调整大小的元素。
关于Javascript - 图像更改大小调整为完整背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343532/