简体   繁体   中英

HTML, jQuery, CSS - Width() returning entire page width instead of div on page load?

So I'm trying to have a function apply "padding-bottom" in a div when a page is loaded, the only problem is that the width returns the entire document value instead of the div value. When I use another function (that changes between images) the function works fine.

$(window).load(function () {
  $('.photoset').each(function () {
    $items = $(this).find('img')

    function get_height(target) {
      return (($items.eq(target).height() / $(this).width()) * 100) + '%';
     }
      $items.css({ paddingBottom: get_height(0) });
  });
}

The Css is as follow:

.photowrapper{
    width:60%;
    margin:auto;
}
.photoset {
    position: relative; 
    display: block;   
    margin:auto;
    overflow:hidden;
}
.photoset figure{
    width: 100%;
    margin: 0;
    padding: 0;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    text-align:center;
}

.photoset img {
    opacity: 0;
    transition:opacity 1.2s;
    max-width:100%;

}
.photoset .photoset-show img{
    opacity: 1;
}

And the HTML

 <div class="photowrapper">
   <div class="photoset center-block">

    <figure class="photoset-show">
     <img src="/images/5220a574-77a8-4aa6-aecc-aedf60eed6e2.jpg" />
    </figure>
    <figure class="">
     <img src="/images/9e59af1e-de75-4ddb-b091-f816224d9f6e.jpg" />
    </figure>
    <figure class="">
      <img src="/images/ad76e5e3-5780-4f22-bcb4-8106fc41161a.jpg" />
    </figure>

 </div>
</div>

This function works as intended, it returns the right width value when switching between images:

        var showCurrent = function (photoset) {
        $items = photoset.find('figure');
        $images = photoset.find('img');
        var counter = photoset.data('counter');
        var numItems = $items.length;
        var itemToShow = Math.abs(counter % numItems);
        $items.each(function () {
            $(this).removeClass('photoset-show');
        })
        function get_height(target) {
            return (($images.eq(target).height() / photoset.width()) * 100) + '%';
        }
        photoset.animate({ paddingBottom: get_height(itemToShow) }, 400);
        $items.eq(itemToShow).addClass('photoset-show');

    };

this isn't what you think it is inside get_height() . It has a different context inside the function. Store a reference to this or pass it in as an argument

Try

$(window).load(function () {
  $('.photoset').each(function () {
    var $photoset = $(this), $items = $photoset.find('img')

    function get_height(target) {
      return (($items.eq(target).height() / $photoset.width()) * 100) + '%';
     }
      $items.css({ paddingBottom: get_height(0) });
  });
}

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