当用户按下页面时,我试图让jquery向下滚动部分的高度(响应):
<section class="intro viewportheight_min" id="intro">
...
</section>
<section id="page2">
...
</section>
<section c id="page3">
...
</section>
全高度部分的css:
body, html, .container, section {
height: 100%;
margin:0;
}
这是js:
var ar=new Array(33,34,35,36,37,38,39,40);
$(document).keydown(function(e) {
var key = e.which;
// PgUp(33), PgDn(34), End(35), Home(36), Left(37), Up(38), Right(39), Down(40)
if( key==33 ) {
$(document).scrollTop( $(document).scrollTop() - $(window).height() );
}
if( key==34 ) {
$(document).scrollTop( $(document).scrollTop() + $(window).height() );
}
return true;
});
但这不起作用,它几乎位于最后一节的底部。
答案 0 :(得分:2)
使用此逻辑调整代码。适用于所有元素,即使它们的高度不同
var positionMap = {};
$('section').each(function(){
var $this = $(this);
positionMap.push({ height: $this.outerHeight(true), position: $this.offset() });
}
$(document).keydown(function(e) {
var key = e.which;
//the current scroll position
var currentPos = $('body').scrollTop();
if( key==33 ) {
//Find next section position
for (var i=0; i<positionMap.length; i++)
{
var e = positionMap[i];
//found the pre
if (e.position.top > currentPos){
destination = e.position.top;
break;
}
}
}
else if( key==34 ) {
//Find previous section position
for (var i=0; i<positionMap.length; i++)
{
var e = positionMap[i];
//found the pre
if (e.position.top + e.height >= currentPos){
destination = e.position.top;
break;
}
}
}
$('body').scrollTop(destination);
return true;
});
答案 1 :(得分:1)
未经测试,但你可以尝试改编:
$(document).keydown(function(e) {
var key = e.which;
//Find first visible section
$el = $('section').filter(':visible').first();
if( key==33 ) {
//Find next section position
var offset = $el.next().offset();
$(document).scrollTop( offset.top );
}
if( key==34 ) {
//Find previous section position
var offset = $el.prev().offset();
$(document).scrollTop( offset.top );
}
return true;
});
此外,我假设33和34是正确的键码fr页面上下。