我想制作一个元素动画,为此,我需要获取上一个元素[.as-body-wrap]
的高度,并以样式将其用作顶部[.as-toaster.is_open]
下方元素的缩进量>
这是我的HTML和jQuery:
jQuery(document).ready(function() {
const cta = document.querySelector('.as_header');
const footer = document.querySelector('.as-toaster');
const expandIcon = document.querySelector('.expand_icon');
const asheight = document.querySelector('.as-body-wrap').offsetHeight;
function toggleFooter() {
footer.classList.toggle('is_open');
expandIcon.classList.toggle('is_reversed')
}
cta.addEventListener('click', toggleFooter);
// onclick action not the best implementation
$(cta).toggle(
function() {
$('.as-toaster.is_open').css('margin-top', -asheight);
},
function() {
$('.as-toaster').css('margin-top', '');
}
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
<div class="as-body-wrap">
<h3 class="as-title">Hi! I am Andrey</h3>
<p class="as-sub-title">fashion designer</p>
<div class="as-description">
<p>Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</div>
</div>
<div class="as-toaster">
<div class="as-wrapper">
<header class="as_header">
<div class="as-contact">Contact Me</div>
<div class="as-contact-info">Please send me an email by filling out the form below.</div>
<svg class="expand_icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
<path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"></path>
<path d="M0 0h24v24H0z" fill="none"></path>
</svg>
</header>
</div>
</div>
</div>
接下来是在.as-toaster.is_open
边距顶部添加样式:-.as-body-wrap
高度
看起来像这行,
$('.as-toaster.is_open').css('margin-top', - asheight);
但是如何以横向方式获得该高度,以防在横向模式下看到该高度时会发生变化
答案 0 :(得分:1)
如果我正确理解这一点,则只需要一种方法即可在运行动画之前获取.as-body-wrap
div的高度。
可以使用jQuery的height function:
$(".as-body-wrap").height();
这将返回所选元素的当前计算高度。
jQuery(document).ready(function() {
const cta = document.querySelector('.as_header');
const footer = document.querySelector('.as-toaster');
const expandIcon = document.querySelector('.expand_icon');
let asBody = $(".as-body-wrap");
let asheight = 0;
function setASBodyHeight() {
asheight = asBody.height();
console.log(`Set asheight to ${asheight}`);
}
function toggleFooter() {
footer.classList.toggle('is_open');
expandIcon.classList.toggle('is_reversed')
}
cta.addEventListener('click', toggleFooter);
setASBodyHeight();
$(window).resize(setASBodyHeight);
// onclick action not the best implementation
$(cta).toggle(
function() {
let asheight = $('.as-body-wrap').height();
$('.as-toaster.is_open').css('margin-top', -asheight);
},
function() {
$('.as-toaster').css('margin-top', '');
}
);
});