简体   繁体   中英

Remove height value from Javascript

I have created a responsive site and then used some JS code to create captions on the images which works fine but when I re-size the browser. The images don't scale like they should and I believe its due to being given a height value in the JS. How do I remove this value and make the caption work?

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

I think you should try 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");
    });
});

I refactored your code and created a fiddle:

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

jQuery.resize() will solve this for you http://api.jquery.com/resize/

You just have to store that procedural code to be re-executable (function) and then retrigger it based on relative (parent) DOM dimensions.

'use strict';

removeHeight(){
    // That code here
}

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

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

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