简体   繁体   English

实现向下滚动 - 通过按住单击向上滚动按钮

[英]Implement scroll down - scroll up buttons by holding down click on them

I have two images, each one of them represents a button to scroll up or down on the site.我有两张图片,每一张都代表一个在网站上向上或向下滚动的按钮。 Here I attach the two images:这里我附上两张图片:

btn-向上滚动

btn-向下滚动

I have added the images with the following code:我使用以下代码添加了图像:

 <img src="https://certifiedgoldexchange.com/wp-content/uploads/2021/05/btn-scroll-down.png" alt="scroll" id="btn-scroll-down">
 <img src="https://certifiedgoldexchange.com/wp-content/uploads/2021/05/btn-scroll-up.png" alt="scroll" id="btn-scroll-up">

my javascript code for scrolling is the following:我的 javascript 滚动代码如下:

var scrollup = document.getElementById("btn-scroll-up");
var scrolldown = document.getElementById("btn-scroll-down");
scrollup.addEventListener("mousedown", function(){  window.scrollBy(0, -100);})
scrolldown.addEventListener("mousedown", function(){  window.scrollBy(0, 100);})

Everything works fine, but I want it to also work by holding down the click on them, how could I solve it?一切正常,但我希望它也可以通过按住它们的点击来工作,我该如何解决? I appreciate your help.我感谢您的帮助。

You need to addEventListener to both mouse down and up.您需要将EventListener 添加到鼠标向下和向上。 Then have a interval timer when the mouse is down and not released.然后在鼠标按下且未释放时有一个间隔计时器。 And, clear the interval if mouse released.并且,如果释放鼠标,则清除间隔。

I added a pos html element to show which image is clicked and held (Since I don't have all your HTML and CSS code), but you can modify the window.scrollBy method to have it scroll the page. I added a pos html element to show which image is clicked and held (Since I don't have all your HTML and CSS code), but you can modify the window.scrollBy method to have it scroll the page.

 var pos = document.getElementById("pos"); var number = pos.innerHTML; var timeOut = 0; var scrollFun = function(e) { if (e.type == "mousedown") { timeOut = setInterval(function() { if (e.target.id == "btn-scroll-up") number -= 100; else number += 100 pos.innerHTML = number; window.scrollBy(0, -100); }, 100); } if (e.type == "mouseup") { clearInterval(timeOut); } }; document.getElementById("btn-scroll-down").addEventListener("mousedown", scrollFun, false) document.getElementById("btn-scroll-down").addEventListener("mouseup", scrollFun, false) document.getElementById("btn-scroll-up").addEventListener("mousedown", scrollFun, false) document.getElementById("btn-scroll-up").addEventListener("mouseup", scrollFun, false)
 <img src="https://certifiedgoldexchange.com/wp-content/uploads/2021/05/btn-scroll-down.png" alt="scroll" id="btn-scroll-down"> <img src="https://certifiedgoldexchange.com/wp-content/uploads/2021/05/btn-scroll-up.png" alt="scroll" id="btn-scroll-up"> <p> pos <span id="pos">0</span> </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM