【问题标题】:HTML, jQuery, CSS - Width() returning entire page width instead of div on page load?HTML,jQuery,CSS - Width() 在页面加载时返回整个页面宽度而不是 div?
【发布时间】:2016-02-03 01:35:39
【问题描述】:

所以我试图在加载页面时在 div 中应用“padding-bottom”函数,唯一的问题是宽度返回整个文档值而不是 div 值。当我使用另一个功能(在图像之间更改)时,该功能可以正常工作。

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

CSS如下:

.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;
}

还有 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>

这个函数按预期工作,它在图像之间切换时返回正确的宽度值:

        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) 中的get_height 是什么?
  • @guest271314 它应该是'.photoset' div。

标签: javascript jquery html css


【解决方案1】:

this 并不是您认为的get_height() 内部的内容。它在函数内部有不同的上下文。存储对this 的引用或将其作为参数传入

试试

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

【讨论】:

  • 效果惊人!想解释一下我的回报是什么?提前致谢。
  • 还要养成在声明变量时总是使用var 的习惯,否则总是将变量放在全局命名空间中会遇到意想不到的结果
  • 简单到发现自己...console.log(this)
猜你喜欢
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 2016-08-28
  • 2021-06-02
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多