Jquery计算数学在小型设备中无法正常工作



我正在制作一个标题,其中在中间有一个响应img。我想计算2个div。img顶部的1;img底部有1个;计算是可以的,除了在小型设备中。

在第一次加载页面时,情况如下:https://i.stack.imgur.com/7jzRZ.png如果我重新加载页面,会发生以下情况:https://i.stack.imgur.com/8IbDg.png

它只发生在小于440px 的屏幕上

这是我正在使用的Jquery:

$(document).ready(function() {
    $(window).resize(function() {
        getWidthAndHeight();
    });
    $(window).load(function() {
        getWidthAndHeight();
    });
});
function getWidthAndHeight (){
    var full    = $('.header-main').outerHeight (),
        hImg    = $('.hd-m-m').height (),
        x       = hImg,
        y       = full - x,
        c1      = y * 0.3,
        c2      = (y * 0.7) + 5,
        ct      = c1 + c2 + x; //used only to confirm the result - console.log
    $('.hd-m-t').css({'height': c1});
    $('.hd-m-b').css({'height': c2});
}

Ps.:我有"+5",因为我使用了一个页边空白:-5px来覆盖img后面的一个小空白区域。

这是我的HTML

<header id="home" class="full"><!-- home -->
    <div class="header-bg"></div><!-- background images -->
    <div class="header-main">
        <div class="hd-s"></div> <!-- div on left side -->
        <div class="hd-m">
            <div class="hd-m-t"></div> <!-- top div - needs calc -->
            <div class="hd-m-m"> <!-- middle div -->
                <img src="img/home/home-logo.png" />
            </div>
            <div class="hd-m-b"> <!-- bottom div - needs calc -->
                <h2>main text</h2>
                <h2>sub text</h2>
            </div>
        </div>
        <div class="hd-s"></div> <!-- div on right side -->
    </div><!-- transparent logo -->
</header>

这是我想要的最终结果:https://i.stack.imgur.com/epGUL.jpg我想这样做,因为背景img会有视差效果,我希望它看起来只会破坏徽标的透明度。

有人能帮我吗?

好的,所以,过了一段时间,我没有找到任何东西来解决这个问题,只有这个"修复"。我不知道这是否是最好的方式,但我们开始了:

我更改了$(document).ready部分,所以现在它在加载完所有内容(包括img)后执行函数。这解决了底部多余的余量。

$(document).ready(function() {
    $(window).load(function() {
        getWidthAndHeight();
    });
    $(window).resize(function() {
        getWidthAndHeight();
    });
});

由于底部缺失的背景只发生在小于440px的屏幕上,我用一个额外的calc为函数添加了一个if条件。缺失的背景总是相同的高度。但我也移动了$(文档)中的函数。准备好了,这是最后的代码:

$(document).ready(function() {
    $(window).load(function() {
        getWidthAndHeight();
    });
    $(window).resize(function() {
        getWidthAndHeight();
    });
    function getWidthAndHeight (){
        var full    = $('.header-main').outerHeight (),
            hImg    = $('.hd-m-m').height (),
            x   = hImg,
            y   = full - x,
            c1  = y * 0.3,
            c2  = (y * 0.7) + 5,
            c3  = c2 + 17,
            ct  = c1 + c2 + x;
        $('.hd-m-t').css({'height': c1});
        if ($(window).width() < 440) {
            $('.hd-m-b').css({'height': c3});
        } else {
            $('.hd-m-b').css({'height': c2});
        };
    }
});

如果有人知道更好的答案,我将不胜感激=D谢谢@SableFost,你给了我一些好的建议(甚至是学习额外的东西)。

最新更新