我有一個modal按鈕,當用戶滾動modal 30px時,它應該出現,當用戶自己回到modal頂部時,它就會消失。 但遺憾的是效果不如預期。滾動30px后按鈕出現,但不會消失。
// Logic for get to top button
let getToTopButton = document.getElementById('btn-back-to-top');
// When user scrolls down 30px, show the button
document
.getElementById('myFlix-react-case-study')
.addEventListener('scroll', scrollFunction);
function scrollFunction() {
if (document.body.scrollTop > 30 || document.documentElement.scrollTop > 30) {
getToTopButton.style.display = 'block';
} else {
getToTopButton.style.display = 'none';
}
}
.modal-container {
position: fixed;
padding: 20px;
box-sizing: border-box;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
/* to show it above other content */
z-index: 999;
/* to allow scrolling if the screen is not high enough*/
overflow: scroll;
/* this is used to center the modal */
display: grid !important;
text-align: center;
}
.case-study-modal {
margin: 80px auto 0px;
display: inline-block;
box-sizing: border-box;
background: #fff;
padding: 20px 30px;
width: 100%;
max-width: 1100px;
text-align: left;
border-radius: 15px;
color: var(--primary-color);
position: relative;
}
.button-up-container {
position: absolute;
right: 38px;
top: 600px;
width: 41px;
}
#btn-back-to-top {
position: fixed;
background: var(--primary-color) linear-gradient(to bottom right, var(--primary-color) 25%, var(--accent-color));
border: none;
border-radius: 10px;
color: var(--font-color);
padding: 8px 16px;
font-size: 22px;
display: none;
}
<div id='myFlix-react-case-study' class="d-none modal-container ">
<div class='case-study-modal'>
<div class="button-up-container">
<button type="button" id="btn-back-to-top">
<i class="fas fa-arrow-up"></i>
</button>
</div>
<div class="modal-title">
<p>
Some title
</p>
</div>
<div class="modal-content">
<p>
Some content
</p>
</div>
當我將scrollTop專門用于modal-container時,我得到了預期的行為,這是通過id實現的,而不是將scrollTop用于body或documentElement。所以我只為“scrollFunction”修改了JavaScript,如下所示:
function scrollFunction() {
console.log('modal scrolled');
if (
document.getElementById('myFlix-react-case-study').scrollTop > 50
) {
getToTopButton.style.display = 'block';
} else {
getToTopButton.style.display = 'none';
}
}