Javascript Jquery弹出窗口未居中

Javascript Jquery弹出窗口未居中,javascript,jquery,html,css,popup,Javascript,Jquery,Html,Css,Popup,我正在开发我的网站,我的弹出窗口显示有问题。单击图片时,会调用一个函数以将图片放入弹出窗口。问题是当我第一次点击图片时,它没有在窗口中居中,第二次它居中。这很奇怪,也许我的函数中的上边距和左边距的计算不太好 JS: 如果您想在页面照片中看到问题: 无论如何,感谢您的帮助:对于与我有相同问题的人,我找到了解决方案,这是因为在加载图片之前加载了弹出窗口,因此位置取决于弹出窗口的大小。由于加载图片前弹出窗口是空的,因此会计算位置。听起来像是图像没有加载,中心取决于图像尺寸 一种可能的解决方案是从图像标

我正在开发我的网站,我的弹出窗口显示有问题。单击图片时,会调用一个函数以将图片放入弹出窗口。问题是当我第一次点击图片时,它没有在窗口中居中,第二次它居中。这很奇怪,也许我的函数中的上边距和左边距的计算不太好

JS:

如果您想在页面照片中看到问题:


无论如何,感谢您的帮助:

对于与我有相同问题的人,我找到了解决方案,这是因为在加载图片之前加载了弹出窗口,因此位置取决于弹出窗口的大小。由于加载图片前弹出窗口是空的,因此会计算位置。

听起来像是图像没有加载,中心取决于图像尺寸

一种可能的解决方案是从图像标记获取图像源,并将其加载到虚拟图像节点中。然后检查虚拟图像节点上的尺寸。您可以直接使用这些尺寸,调整div的大小并使其居中,或者计算纵横比,将高度或宽度设置为100%,然后使div居中。然后,您最终将图像加载到内部

下面是一些可能会让您开始的代码

示例HTML

<!-- Store image with data-src to prevent image from loading (if you want) -->
<img data-src='img.png'>
示例jQuery

// Image source
var imageSource = $('img').attr(imageSourceAttribute);

// Create image element
$('<img>').attr('src', imageSource).load(function() {

  // Native image dimensions
  // Note: $(this) won't work on in-memory images
  var nativeWidth = this.width,
      nativeHeight = this.height;

  // ... Do more things ...

  // Load image
  $('image').attr('src', imageSource);
});

我知道您正在使用引导为什么不能使用modelbox而不是自定义弹出窗口?您不能使用相对位置,然后使用自动边距吗?然后,你只需要计算利润率顶部,或者给它一个百分比,这样它总是大约是顶部的10%,谢谢;但我认为创建自己的函数比直接使用库要好。每个人都可以做,使用教程和复制/粘贴,我没有注意到这一点。显然你已经解决了这个问题。看看我的答案吧。这可能会有帮助。非常感谢你的帮助。非常好,谢谢你的回答。我想我会听从你的建议,因为对我来说,我设置了一个setTimeout,但如果用户的网速很低,问题就不会改变,图片的加载时间会很长。是的,setTimeout不是很可靠,依我看。这是一个更具体的解决方案。
    h1#titlePopup {
  margin-top: -50px;
  color: white;
  text-shadow: 0px 0px 9px black;
}

div#photoPopup {
  padding: 0px 0px 0px 0px;
}

#fade { /*--Black opaque mask background--*/
  display: none; /*--default mask--*/
  background: #000;
  position: fixed; left: 0; top: 0;
  width: 100%; height: 100%;
  opacity: .4;
  z-index: 9999;
}
.popup_block{
  display: none;
  background: #fff;
  padding: 20px;
  border: 10px solid #ddd;
  float: left;
  font-size: 1.2em;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 99999;
  -webkit-box-shadow: 0px 0px 20px #000;
  -moz-box-shadow: 0px 0px 20px #000;
  box-shadow: 0px 0px 20px #000;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 5px;
}

/*--position fixed for IE6--*/
*html #fade {
position: absolute;
}
*html .popup_block {
position: absolute;
}
<!-- Store image with data-src to prevent image from loading (if you want) -->
<img data-src='img.png'>
// Image source
var imageSource = $('img').attr(imageSourceAttribute);

// Create image element
$('<img>').attr('src', imageSource).load(function() {

  // Native image dimensions
  // Note: $(this) won't work on in-memory images
  var nativeWidth = this.width,
      nativeHeight = this.height;

  // ... Do more things ...

  // Load image
  $('image').attr('src', imageSource);
});