javascript - 通过偏移数学居中在非 webkit 浏览器中不起作用

标签 javascript cross-browser

代码:http://jsfiddle.net/LPF85/6/

在 FF、IE7 和 IE9(我测试过的唯一不运行 WebKit 的浏览器)中,left 属性似乎总是​​设置为 0,或者在 IE 中情况,阴性。

我的定位代码完全基于文档的尺寸。

function open_img_in_face_box(id, width){
    max_width = $j(document).width();
    max_height = $j(document).height();
    padding = 150;

    passed_width = width || (max_width - (2 * padding));

    var img = $j('#' + id); 
    dom_img = document.getElementById(id); 

    $j(document).bind('reveal.facebox', function() { 
        $j("#facebox .image img").width(passed_width);
    })
    // display 
    jQuery.facebox({ 
        image: img.attr('src')
    });

    // center and adjust size
    var aspect_ratio = img.width() / img.height();
    var img_width = passed_width;
    var img_height = passed_width / aspect_ratio;

    window_center_y = max_height / 2;
    window_center_x = max_width / 2;

    offset_y = window_center_y - (img_height / 2);
    offset_x = window_center_x - (img_width / 2);

    var fbx = $j('#facebox');
    fbx.css('position', 'absolute');
    fbx.css('left', offset_x + 'px !important');
    fbx.css('top', offset_y + 'px !important');
    fbx.css('margin-left', 'auto');
    fbx.css('margin-right', 'auto');

}

margin-leftmargin-right 在这里似乎没有做任何事情,我对此很满意,因为左边的数学应该适用于所有浏览器,正确的? (这只是数学)

facebox/lightbox 的目标是水平和垂直居中。

最佳答案

为什么您首先要以编程方式计算位置?如果用户调整页面大小怎么办?这可以通过纯 CSS 轻松完成。

我不太明白你的 jsFiddle (或者我没有看到同样的东西?)所以我只给你这个脚本:http://jsfiddle.net/minitech/8U4Ke/您可以随意修改它。它被注释。 ;)

现在可以轻松隐藏和显示 - 隐藏、淡出.overlay。要显示,请淡入。要更改内容,请替换 .popup 中的 HTML。随意添加关闭框之类的东西。

关于javascript - 通过偏移数学居中在非 webkit 浏览器中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6947976/

相关文章:

php - 我的域名前缀搞乱了...我该如何解决这个问题?

javascript - 如果找不到数据,ag-grid 将所有内容隐藏在列标题下方

javascript - 在 HTML 中包含 JavaScript 文件将不能作为 <script …/>

javascript - 状态未立即更新时的 ReactJS 表单验证

html - 针对 Chrome 和 safari,但不是 iphone 或 ipad 上的 Safari?

html - CSS 在 IE 中搞砸了(就像一半的 CSS 没有加载)

javascript - 在 JS 中选中时,我无法读取非默认单选按钮的值

html - IE9 和单元格间距

javascript - 如何在不支持的浏览器上正确模拟 requestAnimationFrame?

javascript - 使用 jquery IE 10 与 Chrome 的缓慢/滞后单选按钮