Jquery弹出菜单未居中

Jquery Popup not centered

本文关键字:菜单 Jquery      更新时间:2023-09-26

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

JS:

function popup(rel, size){
    var popID = rel; //Find popup
    var popWidth = size; //find width
    //make display the popup
    $('#' + popID).fadeIn().css({ 'width': popWidth});
    //Releasing of margin, that allow to center the window 
    var popMargTop = ($('#' + popID).height()+20) / 2;
    var popMargLeft = ($('#' + popID).width()+20) / 2;
    //Apply Margin to Popup
    $('#' + popID).css({
      'margin-top' : -popMargTop,
      'margin-left' : -popMargLeft
    });
   // appearance of the background - .css({'filter' : 'alpha(opacity=80)'}) to correct bugs of oldest version of IE
    $('body').append('<div id="fade"></div>');
    $('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
    return false;
}

HTML:

    <div id="photoPopup" class="popup_block">
</div>

CSS:

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

如果您想在页面"照片"中看到问题:http://manuelmenneveux.pusku.com

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

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

听起来图像还没有加载,居中依赖于图像尺寸。

一种可能的解决方案是从图像标签中获取图像源,并将其加载到伪图像节点中。然后,您将检查该伪图像节点上的尺寸。你可以直接使用这些尺寸和大小并将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);
});