我想根据背景图片大小自动调整div。
用css可以吗?
我还需要使用jquery更新背景图像。
到现在为止,我有:Resize div
更新:JSFiddle链接:Updated Link是否更容易将hand
放在图像元素上方而不是为div设置背景图像?
答案 0 :(得分:0)
不,这对css来说是不可能的,但如果你用jQuery替换背景图像,可以在同一时刻用javascript调整div的大小。
示例:
var url = "some_url_to_image", image_width, image_height;
var img = new Image();
img.onload = function() {
image_width = this.width;
image_height = this.height;
}
image.src = url;
如果要将元素放在另一个元素的顶部,可以使用绝对定位。
答案 1 :(得分:0)
使用css no目前无法使用javascript执行此操作,如下所示。
设置背景图片
$("#yourdiv").css("background-image", "your url");
要获得背景图像的高度或宽度,这样的真正痛苦应该起作用
$.fn.getBgImage = function(callback) {
var height = 0;
var path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '');
var tempImg = $('<img />');
tempImg.hide(); //hide image
tempImg.bind('load', callback);
$('body').append(tempImg); // add to DOM before </body>
tempImg.attr('src', path);
$('#tempImg').remove(); //remove from DOM
};
// usage
$("#background").getBgImage(function() {
console.log($(this).height());
});