简体   繁体   中英

.height() .width() doesn't adjust to change in size

I have an image that adjusts to screen size but the .height and .width() doesn't adjust, leaving my margin-left and margin-top from changing. Is there a way to make it adjust?

    var $src = $(this).attr("href");
    $('#overlay').append('<img class="image" src="' + $src + '" />'); 
    var $image = $('img');
    $('.image').css('max-height','80%');
    $('.image').css('max-width','90%');
    $('.image').css('position', 'fixed');
    $('.image').css('top', '50%');
    $('.image').css('left', '50%');
    var $height = $image.height();
    var $width = $image.width();
    $('.image').css('margin-top', (($height/2)*-1));
    $('.image').css('margin-left', (($width/2)*-1)); 

http://jsfiddle.net/a8a4Y/

The problem is that the image isn't loaded when you messure it. So height, width will always be zero.

http://jsfiddle.net/W8sNw/

So what you can do is to add a handler for the load event and when that is fired you could execute your code:

var $src = $(this).attr("href");
$('#overlay').append('<img class="image" src="' + $src + '" />'); 
var $image = $('img');
$image.on("load",function(){ // This is the new stuff, it listen to the load event 
                             // which is fired when the image is loaded and the size
                             // size is known

   var $height = $image.height();
   var $width = $image.width();
   $('.image').css('margin-top', (($height/2)*-1));
   $('.image').css('margin-left', (($width/2)*-1)); 
   console.log("Height: " + $height);
   console.log("Width: " + $width);
})

I also included an example which a more optimized code. For example every time you use a selector the JavaScript will search in the DOM for that element. You should only to this once, have a look at: http://jsfiddle.net/W8sNw/2/

Try this:

var $src = $(this).attr("href");
    $('#overlay').append('<img class="image" src="' + $src + '" />'); 
    var $image = $('img')
$image.ready(function(){

    $('.image').css('max-height','80%');
    $('.image').css('max-width','90%');
    $('.image').css('position', 'fixed');
    $('.image').css('top', '50%');
    $('.image').css('left', '50%');
    var $height = $image.height();
    var $width = $image.width();
    $('.image').css('margin-top', (($height/2)*-1));
    $('.image').css('margin-left', (($width/2)*-1)); 
});

The jquery resize event might help.

Put your code into a function and call the function in the resize event.

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