jQuery灯箱图像位置问题

时间:2017-03-28 02:44:32

标签: javascript jquery css gallery image-gallery

我已经编写了一个自定义模态窗口图像库/灯箱,并且在图像定位方面存在一些问题。基本上,当您选择图像并按顺序点击时,一切都很好,但如果您退出图像然后重新打开相同的图像,则位置偏离右侧。我不知道可能是什么问题。我有< img>定位绝对和容器相对。我已将图像的CSS设置为左:50%;和顶部:50%;然后使用JS计算负的左上边距。任何人都知道为什么重新打开图像时位置会发生变化? Jsfiddle链接如下。在此先感谢!!

CSS:

#photoViewer {
   display: inline-block;
   position: relative;
   margin: 0 auto;
}
#photoViewer img {
   position: absolute;
   top: 50%;
   left: 50%;
   max-height: 70vh; 
}

利润的JS:

$img.css({
    marginLeft: -$img.width() / 2,
    marginTop: -$img.height() / 2
})

和容器div的大小:

function adjustSize() {
var $width = $current.width();
var $height = $current.height();
$frame.css({
    width: $width,
    height: $height
});

}

(我从Jon Duckett' Javascript& jQuery"书中获得了很多这些代码但是已经调整了它并结合了几个不同的元素/想法。)

链接到jsFiddle:https://jsfiddle.net/jessereitz1/6nxg21a3/1/

1 个答案:

答案 0 :(得分:0)

您的以下功能存在问题 -

function adjustSize() {
  var $width = $current.width();
  var $height = $current.height();
  console.log($width,$height);  /*Debug in console*/
  $frame.css({
    width: $width,
    height: $height
  });
}

首次点击上方的功能返回width:200height:133

在第二次点击上方,功能返回width:0height:0

  

这就是造成这类问题的原因。

$cache = {}的另一个问题是,cache[src].$img对象未获得缓存图片的widthheight属性。

function changeImg(index) {
  var $img;
  var src = $thumbnails[activeIndex].href;
  request = src;

  /*if(cache.hasOwnProperty(src)){
    if(cache[src].isLoading === false) {
        $frame.append(cache[src].$img);
        crossfade(cache[src].$img);
    }
  }else*/{
    $img = $('<img/>');
    cache[src] = {
        $img: $img,
        isLoading: true
    };

    $img.on('load', function() {
        $img.hide();
        $frame.removeClass('isLoading').append($img);
        cache[src].isLoading = false;
        if (request === src) {
            crossfade($img);
        }
    });

    $frame.addClass('isLoading');

    $img.attr({
        'src': src,
        'alt': $thumbnails[activeIndex].title || ''
    });
  }
}

不检查缓存,它提供了正确的结果。