我有以下Jquery,它将向上和向下滑动画布。它是针对特定高度编写的,即200px盒子移动-200px。我想改变它,以便盒子可以是任何高度。
$(function() {
$('#activator').click(function(){
$('#overlay').fadeIn('fast',function(){
$('#box').animate({'top':'160px'},500);
});
});
$('#boxclose').click(function(){
$('#box').animate({'top':'-200px'},500,function(){
$('#overlay').fadeOut('fast');
});
});
});
我想改变它,以便{'top':' - 200px'}实际上是#box当时的高度。
答案 0 :(得分:0)
如果没有您的确切HTML,有点难以猜测您的HTML实际上是什么样的,因此我实际上无法测试这里写的是什么,但理论上它应该可行。如需更精确的答案,请在相关的HTML和CSS中发帖,我会更新我的答案。
要获得内容的高度,请使用$(...).height()
,通过$(...).outerHeight()
访问内容之外元素的高度,并将值true
传递给{ {1}}函数返回对象的高度,包括任何顶部/底部边距。
.outerHeight()
$(function() {
$('#activator').click(function() {
$('#overlay').fadeIn('fast', function() {
$('#box').animate({
'top': '160px'
}, 500);
});
});
$('#boxclose').click(function() {
var box_height = -1 * $('#box').outerHeight(true);
$('#box').animate({
'top': box_height + 'px'
}, 500, function() {
$('#overlay').fadeOut('fast');
});
});
});
鉴于Javascript中的动画有点过时,许多(如果不是全部)开发人员会建议您尽可能使用CSS来实现,这就是我实际上要实现的目标。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(function() {
$('#activator').on('click', function(e) {
e.preventDefault();
//Make sure the link doesn't do that thing we don't want it to do.
$('#box').toggleClass('visible');
})
})
#box {
position: absolute;
/* We want to have an absolutely positioned element, I assume? */
transition: all 400ms linear;
/*Tell the browser that ALL changes to animatable CSS properties will happen over 400 miliseconds, and occur in a linear way. You could change this to ease-in or ease-out, or make your own bezier curve*/
top: -100%;
/*Have the element start off entirely off screen.*/
}
#box.visible,
#box:target {
/* If we have the visible class to the element, OR the element is the current target (i.e. your URL looks like
website.com/page.html#box, the top will be 160px down. Change this to whatever you'd like.*/
top: 160px;
}
这是一个温和的更改,以防您需要它,以便<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellat, consectetur.</p>
<p>Sequi alias debitis quos provident tenetur quis non odio. Voluptatum.</p>
<p>Illum reprehenderit ducimus delectus. Totam maxime harum, ratione eligendi aut.</p>
<p>Mollitia iusto enim eveniet corporis obcaecati. Veritatis quia velit perspiciatis.</p>
<p>Eveniet repudiandae sed ipsa eos, tempora quidem sit ipsam non.</p>
</div>
<div class="main">
<h3>Hello!</h3>
<a href="#box" id="activator">Activate!</a>
</div>
元素从顶部 始终 160px。它是通过使用#box
实现的,这是代码中唯一真正的变化,因为它有更多的HTML并且CSS样式已经改变。
position:fixed
$(function() {
$('#activator').on('click', function(e) {
var $box = $('#box');
//I hate repeating myself in code.
e.preventDefault();
//Make sure the link doesn't do that thing we don't want it to do.
$box.toggleClass('visible')
})
})
#box {
position: fixed;
transition: all 400ms linear;
top: -100%;
}
#box.visible {
top: 160px;
}