javascript - 在页面加载之前触发 jQuery 代码,这可能吗?

标签 javascript jquery html css

我有以下 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");
    });
});

最佳答案

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

例如,此代码可以在文档就绪事件之外完美运行

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

虽然这段代码什么都不做

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

关于javascript - 在页面加载之前触发 jQuery 代码,这可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711059/

相关文章:

javascript - 拖放功能在触摸设备中不起作用?

html - 如何测试网页上粗体文本的百分比?

jquery - 在 css 中分层编号嵌套订单列表?

php - 设计投票系统

jquery - 未定义方法 `gsub' 2014-10-31 17 :55:55 +0530:Time

html - 两个文本区域以最小宽度并排,但当文本较长时折叠左侧

javascript - 将 Uint8ClampedArray 转换为常规数组

javascript - 禁用拖动图像或链接的重定向

javascript - jQuery ui 组合框在 IE 10 中默认打开

jquery - 如何使用 JSP include 或 c :import or symlink 加载应用程序上下文之外的 Html 页面