我正在尝试使用.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);
});
});
答案 0 :(得分:2)
我在您的代码中进行了一些更改
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);
}
});
});