我有以下 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/