当我单击按钮时,无法弄清楚如何在 js 中向下/向上滚动 50px



这是我目前拥有的代码。我想做的是,当我点击一个按钮-向上移动-我希望area3中的文本向上移动50px。但现在它又一路回到了顶峰。这是一个h/w赋值,如果需要的话,我们正在做非常基本的js/jquery?:(任何帮助都将不胜感激!谢谢

$("#moveUp").click(function(event){
event.preventDefault();
var scrollPos = $(".area").scrollTop();
var newPos = scrollPos - 50;
$(".area3").scrollTop(newPos);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
blah blah
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>

如果我没有错,我认为这可以帮助你:

$("#moveup").click(function(){
$(".area3").css({"margin-top":"-=50px"});
});
$("#moveUp").click(function(event){
window.scrollTo(0, window.scrollY - 50)
})

window.sollTo(x,y(是一种将屏幕滚动到给定坐标的方法,其中x为水平坐标,y垂直坐标。屏幕的左上角是0,0。当window.scrollY得到屏幕的当前垂直位置时,你只需要减去50就可以从你的当前位置向上滚动50px

如果您只想移动area3中的text,则应该使用一些css来正确地使用jQuery实现此行为,使用animate()将一些具有平滑动画的ease添加到文本中。

$("#moveUp").click(function(event){
event.preventDefault();
$('.area3').animate({
position: 'absolute',
bottom: +50
}, 'slow');
})
.area3 {
position: relative;
height: 200px;
}
.area3 span {
position: absolute;
bottom: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
<span>blah blah</span>
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>

但是,如果您想将整个窗口设置为scroll,您可以按照以下方式执行操作,我们使用相同的方法,使用不同的选择器bodyhtml

$("#moveUp").click(function(event){
event.preventDefault();
$('body, html').animate({
scrollTop: -50
}, 500);
})
body, html {
height: 1000px
}
.area3 {
margin-top: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area3">
<span>blah blah</span>
</div>
<div class="area4">
<button id="moveUp">Move Up</button>
</div>

如果你想使用window接口,你可以通过将上面的代码更改为来实现

$("#moveUp").click(function(event){
event.preventDefault();
window.scrollTo(0, -50);
})

通过使用window的这种方法,您可以使它像我们上面所做的那样平稳地移动——您不能使用jQueryanimate()APIjavascript来引发错误——不要这样做。

最新更新