从Javascript中删除高度值

从Javascript中删除高度值

问题描述:

我创建了一个响应网站,然后使用一些JS代码在图像上创建标题,但是当我重新调整浏览器的尺寸时,它们可以正常工作。这些图像没有像他们应该的那样缩放,我相信这是因为在JS中被赋予了一个高度值。如何删除此值并使标题起作用?从Javascript中删除高度值

$(window).load(function(){ 
    // For each instance of p.caption 
    $("p.caption").each(function(){ 
    $(this) 
     // Add the following CSS properties and values 
     .css({ 
      // Height equal to the height of the image 
      "height" : $(this).children("img").height() + "px", 
      // Width equal to the width of the image 
      "width" : $(this).children("img").width() + "px" 
     }) 
     // Select the child "span" of this p.caption 
     // Add the following CSS properties and values 
     .children("span").css(

      // Width equal to p.caption 
      // But subtract 20px to callibrate for the padding 
      "width", $(this).width() - 20 + "px") 

     // find the <big> tag if it exists 
     // And then add the following div to break the line 
     .find("big").after('<div class="clear"></div>'); 

     // When you hover over p.caption 
     $("p.caption").hover(function(){ 

      // Fade in the child "span" 
      $(this).children("span").stop().fadeTo(400, 1); 
      }, function(){ 
      // Once you mouse off, fade it out 
      $(this).children("span").stop().delay(600).fadeOut(400); 
     }); 
    // End $(this) 
    }); 
}); 

我想你应该试试window.resize。

$(window).resize(function() { 
    $("p.caption").each(function() { 
     var item = $(this); 
     var big = item.find("big"); 

     item.css({ 
      "height" : item.children("img").height() + "px", 
      "width" : item.children("img").width() + "px" 
     }).children("span").css("width", item.width() - 20 + "px"); 
    }); 
}); 

我重构代码,并创建了一个小提琴:

http://jsfiddle.net/VinnyFonseca/6Kv9U/1/

+0

感谢。我只注意到,当你缩小浏览器时,它会完美调整大小,但是当你增加浏览器大小时,图像不会缩放。是否有另一个调整大小的功能,让这个工作? – AlistairWilliams 2013-03-20 09:16:11

jQuery.resize()会解决这个你http://api.jquery.com/resize/

你只需要存储的程序代码是重新执行(功能),然后再触发它基于亲属(父母)DOM尺寸。

'use strict'; 

removeHeight(){ 
    // That code here 
} 

$(document).ready(function(){ 
    // Initial removal 
    removeHeight(); 

    // Removal when resizing 
    $(window).resize(function() { removeHeight() }); 
});