我有一个网络应用程序,我在页面中创建一个可滚动的元素。这是可滚动页面中的可滚动元素,对于具有触摸屏和智能手机设备的人来说这是困难和恼人的。相反,对于较小的设备,我实现了滚动按钮。而不是滚动条滚动,将有一个" up" " down"按钮。如何防止计数器在元素底部递增一次?
以下是代码:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta name="author" content="Hayden Bradfield"/>
<style type="text/css">
button{display:block;}
div{width:100px;height:100px;border:1px solid black;overflow:hidden;}
</style>
</head>
<body>
<button id="scrollup">Up</button>
<div id="container">
<p>ksmdaksksmd ka sl sla skd ask alk dksas
kc ds k s cdks cjskc s cks jdcksd jd csc k
cdskjdnsj sdkfjks fj sjk jd jf jd ksf dfjks
dsjk js jkf k fjkd jks fj dsjf d fk ks jkf
jdfsd j dsdk jk fjdk sj fjd fks sd abcdef</p>
</div>
<button id="scrolldown">Down</button>
<script type="text/javascript">
var scrollupbut = document.querySelector('#scrollup');
var scrolldownbut = document.querySelector('#scrolldown');
var container = document.querySelector('#container');
var counter = 0;
scrolldownbut.addEventListener('click',function(){
var addvals = counter += 10;
container.scrollTop = counter;
console.log(counter);
});
scrollupbut.addEventListener('click',function(){
if(counter > 0){
counter -= 10;
container.scrollTop = counter;
console.log(counter);
}
});
</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
您可以使用scrollHeight - clientHeight
计算scrollTop的最大值,然后在每次按下scrollDown按钮时检查是否已达到该距离。
const maxScrollTop=container.scrollHeight - container.clientHeight;
if (counter+10<=maxScrollTop) { counter += 10; }
演示:
.as-console-wrapper { max-height: 20px !important; bottom: 0 }
&#13;
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<meta name="author" content="Hayden Bradfield"/>
<style type="text/css">
button{display:block;}
div#container{width:100px;height:100px;margin:10px;border:1px solid black;overflow:hidden;}
</style>
</head>
<body>
<button id="scrollup">Up</button>
<div id="container">
<p>ksmdaksksmd ka sl sla skd ask alk dksas
kc ds k sk fjdk sj fjd fks sd abcdef
ask alk dksas
kc ds k sk fjdk sj fjd fks sd ab</p>
</div>
<button id="scrolldown">Down</button>
<script type="text/javascript">
var scrollupbut = document.querySelector('#scrollup');
var scrolldownbut = document.querySelector('#scrolldown');
var container = document.querySelector('#container');
var counter = 0;
const maxScrollTop=container.scrollHeight - container.clientHeight;
scrolldownbut.addEventListener('click',function(){
if (counter+10<=maxScrollTop) { counter += 10; }
container.scrollTop = counter;
console.log(counter);
});
scrollupbut.addEventListener('click',function(){
if(counter > 0){
counter -= 10;
container.scrollTop = counter;
console.log(counter);
}
});
</script>
</body>
</html>
&#13;