简体   繁体   中英

Automatically re-size div

I would like to automatically resize div according the background-image size.

Is that possible with css?

I also need to update the background-image using jquery.

Until now I have: Resize div

Updated: JSFiddle link: Updated Link Is it easier to place the hand above the image element instead of setting a background-image for the div?

No, that's not possible with css but if you are replacing the background image with jQuery, it's easy to resize the div with javascript at the same moment.

Example:

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;

If you want to position an element on top of another element, you can use absolute positioning.

With css no there is no way to currently do this at the moment you can do it with javascript as shown below.

To set a background image

$("#yourdiv").css("background-image", "your url");

To get background image height or width is a real pain something like this should work

$.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());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM