在页面加载之前触发jQuery代码,是否可能?

Jam*_*don 1 html javascript css jquery

我有以下jQuery当前在产品准备就绪时运行,但它正在做的是调整元素的高度,但看起来很丑,因为它在页面加载后改变高度所以我的问题是:是否可以加载代码和在显示之前设置高度?

$(document).ready(function () {
    // set hero height to max viewport
    var heroHeight = $(window).height();
    var smsHeight = $('#send-text').height();
    $('#oasis-hero').css('min-height', heroHeight - smsHeight - 140 + 'px');

    // hide video
    $('#hero-video').hide();

    // click function to auto play video
    $('.hero-text .primaryCta').on('click touchend', function (e) {
        $("#hero-video")[0].src += "&autoplay=1";
        $('#hero-video').show();
        $('#hero-video-bg').hide();
        $('.hero-text').hide();

        $(this).unbind("click");
    });
});
Run Code Online (Sandbox Code Playgroud)

Cla*_*edi 7

绝对可能.您只需要在相关的html元素定义之后放置代码.您只需要避免引用尚未创建的元素.

例如,此代码将完全在文档就绪事件之外工作

<div id="myDiv"></div>
<script>
    $('#myDiv').hide(); // <-- will hide 'myDiv' since the element is already created
</script>
Run Code Online (Sandbox Code Playgroud)

虽然这段代码什么都不做

<script>
    $('#myDiv').hide(); // <-- won't hide 'myDiv' since the element is not created yet
</script>
<div id="myDiv"></div>
Run Code Online (Sandbox Code Playgroud)