簡體   English   中英

滾動事件停止后的事件?

[英]Event AFTER scroll event stops?

所以我有一個想要添加到欄中的陰影,如以下示例所示:

https://jsfiddle.net/eddietal2/qgLvsx2v/

這是我擁有的JavaScript:

var topBar = document.getElementById('top-bar');
var wrapper = document.getElementById('wrapper');

wrapper.onscroll = function () {
  topBar.style.boxShadow = "10px 20px 30px blue"
}

我要實現的效果是,當用戶滾動時,我希望顯示框陰影,但是當他們停止滾動時,我希望框陰影消失。 我怎樣才能達到這種效果?

沒有“ scrollstop”事件。 您需要確定用戶何時停止滾動自己。

當用戶滾動時,請啟動一個計時器幾十毫秒(您必須使用此值),然后清除所有現有的計時器。 當計時器達到0時,調用您的函數。

您可以使用計時器來檢查是否在最近N毫秒內滾動過,然后在大約該時間之后調用回調。

 var wrapper = document.getElementById('wrapper') function onScroll(element, scrolling, stopped) { let timer = null // bind the event to the provided element element.addEventListener('scroll', function (e) { // use a class to switch the box-shadow on element.classList.add('scrolling') if (typeof scrolling === 'function') { scrolling.apply(this, arguments) } // clear the existing timer clearTimeout(timer) // set a timer for 100 ms timer = setTimeout(() => { // if we get in here the page has not been scrolled for 100ms // remove the scrolling class element.classList.remove('scrolling') if (typeof scrolling === 'function') { stopped.apply(this, arguments) } }, 100) }) } // call the function onScroll(wrapper, function scrolling(e) { e.target.classList.add('scrolling') }, function stopped(e) { e.target.classList.remove('scrolling') } ) 
 * { box-sizing: border-box; } #wrapper { height: 200px; padding: 2em; overflow: auto; transition: .4s box-shadow; } #wrapper.scrolling { box-shadow: 0px 0px 60px blue inset; } #topBar > div { background: #eee; height: 200px; width: 200px; margin-bottom: 1em; position: relative; transition: .4s all; } #wrapper.scrolling #topBar > div { transform: perspective(1200px) translateZ(20px); box-shadow: 2px 2px 10px #777; } 
 <div id="wrapper" class=""> <div class="" id="topBar"> <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div> </div> </div> 

Onscroll易於監視以應用陰影,但是去除陰影是棘手的部分,我能想到的最好的方法是事件mouseout ...

<!DOCTYPE html>
<html>
<head>
<style>

div {
 border: 1px solid black;
 width: 200px;
 height: 100px;
 overflow: scroll;
}

</style>
</head>
<body>

<div onmouseout="this.style.boxShadow='none';" onscroll="this.style.boxShadow='10px 20px 30px blue';">In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.<br><br>
'Whenever you feel like criticizing anyone,' he told me, just remember that all the people in this world haven't had the advantages that you've had.'</div>

</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM