我想创建一个具有以下结构的站点:
- 您进入站点,然后可以从第 1 部分向下滚动到第 2 部分。
- 然后,您需要决定是再次向下滚动一个部分还是开始向右滚动。
这是我滚动得到的结果:
$(function() {
$('a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollLeft: $($anchor.attr('href')).offset().left
}, 1000);
event.preventDefault();
});
});
平滑的水平效果很好,但我无法获得垂直效果,您可以在第 2 和第 3 部分滚动到顶部,但应该没有任何内容。
有什么想法吗?
最佳答案
你可以在 jQuery 中使用 $(window).scrollTop()
和 $(window).scrollLeft()
然后加上或减去高度或宽度视口(viewport):
$(document).ready(function(){
$('.scrollDown').click(function(){
var scrollDown = $(window).scrollTop() + $(window).height();
$('html, body').animate({scrollTop: scrollDown + 'px'}, 600);
});
$('.scrollRight').click(function(){
var scrollRight = $(window).scrollLeft() + $(window).width();
$('html, body').animate({scrollLeft: scrollRight + 'px'}, 600);
});
$('.scrollUp').click(function(){
var scrollUp = $(window).scrollTop() - $(window).height();
$('html, body').animate({scrollTop: scrollUp + 'px'}, 600);
});
$('.scrollLeft').click(function(){
var scrollLeft = $(window).scrollLeft() - $(window).width();
$('html, body').animate({scrollLeft: scrollLeft + 'px'}, 600);
});
});
body {
margin: 0;
width: 200vw;
overflow: hidden;
}
section {
position: relative;
display: block;
width: 100vw;
height: 100vh;
}
button {
position: absolute;
display: block;
top: 48vh;
left: 48vw;
width: 160px;
}
button:nth-last-of-type(3) {
position: absolute;
display: block;
top: 38vh;
}
button:nth-of-type(2) {
position: absolute;
display: block;
top: 48vh;
}
button:nth-of-type(3) {
position: absolute;
display: block;
top: 58vh;
}
.x1y2, .x2y2 {
float: left;
display: inline-block;
}
.x1y3 {
clear:left;
}
.x1y1 {
background-color: rgb(255,0,0);
}
.x1y2 {
background-color: rgb(255,255,0);
}
.x2y2 {
background-color: rgb(0,127,0);
}
.x1y3 {
background-color: rgb(0,0,255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="x1y1">
<button class="scrollDown" type="button">Scroll Down</button>
</section>
<section class="x1y2">
<button class="scrollUp" type="button">Scroll Up</button>
<button class="scrollRight" type="button">Scroll Right</button>
<button class="scrollDown" type="button">Scroll Down</button>
</section>
<section class="x2y2">
<button class="scrollLeft" type="button">Scroll Left</button>
</section>
<section class="x1y3">
<button class="scrollUp" type="button">Scroll Up</button>
</section>
关于javascript - 在一页上启用水平和垂直滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41097953/