gpt4 book ai didi

javascript - 平滑滚动到 div

转载 作者:行者123 更新时间:2023-11-28 10:48:19 25 4
gpt4 key购买 nike

我正在使用 AngularJS 构建一个网站,但我对它还很陌生。但我对 jQuery 很熟悉。在我的网站中,我想平滑滚动到特定的 <div>单击按钮。我在 jQuery 中有一个代码。但我不知道如何在 AngularJS 中编写相同的代码。谁能告诉我如何在 AngularJS 中编写同样的代码?

这是片段

$('#todivone').click(function () {
$('html, body').animate({
scrollTop: $('#divone').offset().top
}, 'slow');
});
$('#todivtwo').click(function () {
$('html, body').animate({
scrollTop: $('#divtwo').offset().top
}, 'slow');
});
$('#todivthree').click(function () {
$('html, body').animate({
scrollTop: $('#divthree').offset().top
}, 'slow');
});
div {height: 900px; border:2px solid #333; padding:10px; margin: 0px;}
button {position: fixed; margin-top: 50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="todivtwo">GOTO DIV 2</button>
<br>
<button id="todivthree">GOTO DIV 3</button>
<br>
<button id="todivone">BACK TO DIV 1</button>
<br>
<div id="divone">DIV CONTENT 1</div>
<div id="divtwo">DIV CONTENT 2</div>
<div id="divthree">DIV CONTENT 3</div>

最佳答案

使用 ng-click 尝试一下

    <button id="divone" ng-click="goToDiv(1)">DIV CONTENT 1</button>
<button id="divtwo" ng-click="goToDiv(2)">DIV CONTENT 2</button>
<button id="divthree" ng-click="goToDiv(3)">DIV CONTENT 3</button>

在 Controller 中:

$scope.goToDiv= function(a){
if(a==1){
$('html, body').animate({
scrollTop: $('#divone').offset().top
}, 'slow');
}
if(a==2){
$('html, body').animate({
scrollTop: $('#divtwo').offset().top
}, 'slow');
}
if(a==3){
$('html, body').animate({
scrollTop: $('#divthree').offset().top
}, 'slow');
}
}

关于javascript - 平滑滚动到 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39062045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com