有没有办法让 offset.top() 响应?如果不是,我如何才能使动画 div 在滚动时响应浏览器的顶部?
在我的 fiddle 中,当您向下滚动时,div
会正确地到达顶部,但如果您在高度方向上滚动屏幕,它就不再按预期运行了。
根据我的理解,这是因为 div 存储的变量被调用了一次,但是当我将它绑定(bind)到滚动事件时,div 没有按预期工作。
fiddle :https://jsfiddle.net/jzhang172/j2yrumyg/8/
$(function(){
var cheese= $('.ok').offset().top; //Define top of 'hey'
//
//Animates when it reaches red part of page
//
$(window).scroll(function() {
if ( $(window).scrollTop() >= cheese ) {
$('.ok').addClass('top');
$('.nice').hide().fadeIn().html('ok');
$(".nice").animate({
left:"0"
}, 600);
$('.nice').addClass('maybe');
}
else{
$('.ok').removeClass('top');
$('.nice').removeClass('maybe');
$('.nice').html('Hey');
}
});
//
//This part doesn't rely on scroll event and is in charge of changing hover on ".ok" div.
//
$('.ok').hover(function(){
if(!$(this).hasClass("top"))
$(this).addClass('proj-hover');
},function(){
$(this).removeClass('proj-hover');
});
//
//Animate on click
//
$('.ok').click(function(){
if ( $(window).scrollTop() >= cheese ) {
}
else{
$("body, html").animate({
scrollTop: $('.other').offset().top
}, 600);
}
});
});
*{
box-sizing:border-box;
}
body,html{
padding:0;
margin:0;
}
.div{
height:100vh;
width:100%;
background:#6464FF;
}
.other{
height:1000px;
width:100%;
background:#FF6161;
}
.ok{
position:absolute;
bottom:0;
left:50%;
margin-left:-100px;
width:200px;
height:50px;
line-height:50px;
background:black;
color:white;
text-align:center;
transition:1s;
}
.top{
position:fixed;
top:0;
left:0;
transition:.7s;
margin-left: 0px;
width:100%;
}
.proj-hover{
background:white;
color:black;
}
.blue{
background:blue;
}
.nice{
transition:0s;
margin: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div">
<div class="ok">
<p class="nice">Hey</p>
</div>
</div>
<div class="other">
</div>
最佳答案
您的代码只是从元素 .ok 开始获取 .top()
。为了让它起作用,您还应该使用不会改变其位置的东西,如 .other 元素。
刚刚在这里更新了您的代码:
$(window).scroll(function() {
var cheese= $('.other').offset().top; //Define top of 'hey'
if ( $(window).scrollTop() >= cheese ) {
...
}
});
更新
但是如果你想根据元素.ok获取位置,你就需要为它创建一个占位符元素。
HTML
<div class="div">
<div class="placeholder">
<div class="ok">
<p class="nice">Hey</p>
</div>
</div>
</div>
<div class="other"></div>
CSS
.ok,
.placeholder{
position:absolute;
bottom:0;
left:50%;
margin-left:-100px;
width:200px;
height:50px;
line-height:50px;
background:black;
color:white;
text-align:center;
transition:1s;
}
JS
$(window).scroll(function() {
var cheese= $('.placeholder').offset().top; //Define top of 'hey'
if ( $(window).scrollTop() >= cheese ) {
...
}
});
关于javascript - jQuery 和 Javascript : offset. top() 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414160/