我试图通过使用.parent,.next和.find来制作一个用于遍历页面的按钮,但出现错误
Uncaught TypeError: Cannot read property 'top' of undefined
的HTML:
<div id="mainbody">
<div class="hero-unit">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
</div>
js:
/********************************
/ SCROLL TO NEXT
/*******************************/
$(document).ready(function(){
$('.next').on("click", function() {
var next;
next = $('#mainbody').parent().next().find(".index-block");
$('html,body').animate({ scrollTop: next.offset().top + 65}, 1000);
});
});
最佳答案
我对您的代码进行了一些更改
的HTML
<div id="mainbody">
<div class="index-block hero-unit">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
<div class="index-block">
<div class="next"></div>
</div>
</div>
的CSS
.hero-unit, .index-block {
background-color: #efefef;
margin: 5px;
height: 200px;
position: relative;
width: 100%;
}
.next {
background-color: #333;
color: #FFF;
height: 50px;
width: 50px;
position: absolute;
bottom: 5px;
right: 5px;
cursor:pointer;
}
jQuery的
$(document).ready(function(){
$('.next').on("click", function() {
if($(this).parent().next(".index-block").offset() != undefined){
var next = $(this).parent().next(".index-block").offset();
$('html,body').animate({ scrollTop: next.top}, 1000);
}
});
});
关于javascript - jQuery滚动到功能不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31592920/