scroll eventListener не работает в javascript - PullRequest
2 голосов
/ 26 апреля 2020

window.addEventListener для события прокрутки не работает в моем JS. Я пробовал несколько способов, но все еще не работает. Я также использовал intersectionObserver в JS. Вот код JS

const moveToAbout = () => {
    document.getElementById('about').scrollIntoView(true)
}

const moveToWork = () => {
    document.getElementById('work').scrollIntoView()
}

const moveToTop = () => {
    document.getElementById('main-section').scrollIntoView(true)
}


const options = {
    root: null,
    threshold: 0,
    rootMargin: "-150px"
}

const header = document.querySelector("header")
const sections = document.querySelectorAll(".section")
const mainSection = document.querySelector(".main-container")

const bttWrapper = document.getElementById('bttBtn-wrapper')
const veganImage = document.getElementById('vegan-store-image')
const navbar = document.getElementById('header')



veganImage.onclick = () => {
    window.open("https://thoughtlessmind.github.io/Vegan-store")
}


const sectionOne = document.querySelector(".about-section");
// bttWrapper.style.display = 'none'

const mainObserver = new IntersectionObserver(function (entries, observer) {
    entries.forEach(entry => {

        if (entry.isIntersecting) {
            header.classList.remove("nav-theme-2")
            bttWrapper.classList.add("btnWrapperHidden")
            bttWrapper.classList.remove("btnWrapperShow")
        } else {
            header.classList.add("nav-theme-2")
            bttWrapper.classList.add("btnWrapperShow")
        }


        // console.log(entry.target, '-', entry.isIntersecting)
    });
}, options);


mainObserver.observe(mainSection)


window.addEventListener("scroll", (event)=>{
    console.log("scrolled")
    var scroll = this.scrollY
    if(scroll > 20){
        console.log('reached')
    }
})

const test = () =>{
    console.log('working')
}

window.addEventListener("scroll", test)

window.addEventListener("scroll", () => console.log(window.pageYOffset));


Позже в нижней части я попытался добавить событие прокрутки, но ничего не происходит. Вот ссылка на весь репо: Ссылка на репозиторий Github

Ответы [ 2 ]

3 голосов
/ 26 апреля 2020

удалить height свойство из CSS main. Работает сейчас:

использовать min-height, max-height

const moveToAbout = () => {
document.getElementById('about').scrollIntoView(true)
}

const moveToWork = () => {
document.getElementById('work').scrollIntoView()
}

const moveToTop = () => {
document.getElementById('main-section').scrollIntoView(true)
}


const options = {
root: null,
threshold: 0,
rootMargin: "-150px"
}

const header = document.querySelector("header")
const sections = document.querySelectorAll(".section")
const mainSection = document.querySelector(".main-container")

const bttWrapper = document.getElementById('bttBtn-wrapper')
const veganImage = document.getElementById('vegan-store-image')
const navbar = document.getElementById('header')



veganImage.onclick = () => {
window.open("https://thoughtlessmind.github.io/Vegan-store")
}


const sectionOne = document.querySelector(".about-section");
// bttWrapper.style.display = 'none'

const mainObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {

    if (entry.isIntersecting) {
        header.classList.remove("nav-theme-2")
        bttWrapper.classList.add("btnWrapperHidden")
        bttWrapper.classList.remove("btnWrapperShow")
    } else {
        header.classList.add("nav-theme-2")
        bttWrapper.classList.add("btnWrapperShow")
    }


    // console.log(entry.target, '-', entry.isIntersecting)
});
}, options);


mainObserver.observe(mainSection)

window.onload = () =>{
console.log("loaded");
window.onscroll = function()
{
  console.log("scrolling.....", window.scrollY);
}
}
@import 'global.css';


/* -----Navigation bar styles */
@import 'navbar.css';



/* ----------- Main contaier styles*/
main{
    overflow: scroll; 
    scroll-snap-type: y mandatory;
}

.section{
    /* scroll-snap-align: start; */
    /* Uncomment above to add snap scrolling effect */
    margin-left: auto;
    margin-right: auto;
    width: 80%;
    max-width: 1100px;
    border-bottom: 1px solid grey;
}

.main-container {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    justify-content: space-between;
}

.name-text{
    font-size: 2.8rem;
    font-weight: 500;
    color: var(--primary-text-color);
}

.intro-text{
    padding: 1rem;
    padding-left: 0;
    font-size: 1.2rem;
    color: var(--para-text-color);
}

.right-container{
    text-align: left;
}

.text-container{
    align-self: center;
}

.left-image{
    width: 200px;
    height: 200px;
    background-color: palegreen;
    animation: rotate 8s infinite ease-in-out ;
}

@keyframes rotate{
    0%{
        border-radius: 0;
    }
    50%{
        border-radius: 50%;
        transform: rotate(145deg);
        background-color: green;
    }
    100%{
        transform: rotate(360deg);
        border-radius: 0;
    }
}



.social-link-container{
    margin-top: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.social-logo{
    font-size: 2rem;
    color: var(--primary-text-color);
}

.social-link{
    margin: 0 10px;
}


/* About section */

.about-section{
    height: 100vh;
    padding-top: 38.5px;
    border-bottom: 1px solid grey;
}

.about-section >  h2{
    padding: 10px 10px 10px 0px;
}


/* ----Work section ---- */

#work{
    height: 100vh;
    padding-top: 38.5px;
}

#work >h2 {
    padding: 10px 10px 10px 0;
}

/* .inverse{
    background-color: #111;
    color: #eee;
} */


.project-card{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border-radius: 5px;
    margin-top: 15px;
    transition: 0.3s;
}

.project-card:hover{
    background-color: rgba(200, 200, 200, 0.2);
}

.left-side-card{
    padding-right: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    max-height: 145px;
    height: 145px;
}



.project-name{
    margin-bottom: 10px;
    display: inline-block;
}

.project-link{
    text-decoration: none;
    letter-spacing: 0.8px;
    position: relative;
}

.project-name::after{
    position: absolute;
    bottom: 0;
    left: 0;
    content: '';
    height: 1px;
    width: 100%;
    background-color: black;
    /* transform: scale(1); */
    transition: 0.3s;
    transform-origin: left;
}

.project-name:hover::after{
    transform: scale(0);
    transform-origin: left;
}

.project-description {
    word-spacing: 0.8px;
    letter-spacing: -0.2px;
}

.project-image{
    height: 150px;
    width: 250px;
    cursor: pointer;
    border-radius: 5px;
}

.tech-stack-container{
    display: flex;
}

.tech-stack{
    margin-right: 10px;
    font-size: 12px;
    font-weight: 600;
    color: rgba(198, 198, 198,0.8);
    transition: 0.3s;
}

.project-card:hover .tech-stack{
    color: #6d6d6d
}

.repo-link{
    margin-left: 20px;
}

.repo-logo{
    color: rgba(0, 0, 0, 0.8);
}

.repo-logo:hover{
    color: rgba(0, 0, 0, 0.6);
}








@media only screen and (max-width: 500px){
    nav{
        display: flex;
        align-items: center;
        justify-content: center;
        float: none;
        height: 22px;
    }
    .section{
        width: 90%;
    }
    .main-container{
        flex-direction: column-reverse;
        justify-content: space-evenly;
    }
    .name-text{
        text-align: center;
        font-size: 28px;
    }

    .intro-text{
        font-size: 18px;
    }

    .project-card{
        flex-direction: column;
    }

    #work{
        min-height: fit-content;
        height: fit-content;
    }
}
header {
    position: fixed;
    width: 100%;
    background: rgba(255, 255, 255, 0.8);
    padding: 10px 0;
    z-index: 1;
    transition: all ease-in-out 0.5s;
}

.green-nav {
    background-color: lawngreen;
}

header:after {
    content: "";
    display: block;
    clear: both;
}

nav {
    float: right;
    padding: 0 10%;
}

nav a {
    font-size: 1rem;
    margin: 5px 10px;
    color: #484848;
    text-decoration: none;
    transition: 0.3s;
    padding-bottom: 2px;
    font-weight: 500;
    position: relative;
    padding: 2px 5px;
    cursor: pointer;
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
}

nav a::after {
    position: absolute;
    bottom: 0;
    left: 0;
    content: '';
    height: 1px;
    width: 100%;
    background-color: #484848;
    transform: scaleX(0);
    transition: 0.5s;
    transform-origin: center;
}


nav a:hover::after {
    transform: scaleX(1);
}

* {
    margin: 0;
    padding: 0;
    scroll-behavior: smooth;
}

:root{
    --primary-text-color: #000;
    --para-text-color: #323232;
}

body {
    font-family: 'Montserrat', sans-serif;
    font-weight: 400;
    /* scrollbar-color: rgba(0, 0, 0, .5);
    scrollbar-track-color: #f1f1f1; */
}

a {
    text-decoration: none;
    color: #000;
}



/*-------- Custom scroll bar and selection -----*/

@media only screen and (min-width: 600px) {
    ::-webkit-scrollbar {
        width: 7px;
    }

    ::-webkit-scrollbar-thumb {
        border-radius: 4px;
        background-color: rgba(0, 0, 0, .5);
        box-shadow: 0 0 1px rgba(255, 255, 255, 0.5);
    }

    ::-webkit-scrollbar-thumb:hover {
        background: rgba(0, 0, 0, .6);
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
}

::selection {
    background-color: rgb(78, 81, 83);
    color: #fff;
}


/* ------- back to top btn */

#bttBtn-wrapper {
    position: absolute;
    bottom: 50px;
    right: 50px;
    background-color: grey;
    border-radius: 50%;
    height: 40px;
    width: 40px;
    cursor: pointer;
}

.btnWrapperHidden {
    transform: scale(0);
    transform-origin: center;
    transition: 300ms;
}

.btnWrapperShow {
    transform: scale(1) rotate(360deg);
    transform-origin: center;
    transition: 300ms;
}

#bttBtn {
    width: 15px;
    height: 15px;
    border-radius: 2dpx;
    border-left: 3px solid;
    border-top: 3px solid;
    transform: rotate(45deg);
    margin: auto;
    margin-top: 11px;
}
image
0 голосов
/ 26 апреля 2020

Попробуйте это

const main = document.querySelector('main');
// main.onscroll = logScroll;

main.addEventListener('scroll', logScroll)

function logScroll(e) {
  console.log(`Scroll position: ${e.target.scrollTop}`);
  if(e.target.scrollTop  == 761){
      console.log('About Page is Reached');
  }
}

Примечание для target.onscroll

Для объекта на объекте может быть назначен только один обработчик прокрутки время. Для большей гибкости вы можете вместо этого передать метод прокрутки методу EventTarget.addEventListener ().

Как объяснено здесь https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onscroll

Как я понимаю здесь, в моем коде выше, target.scrollTop будет работать только тогда, когда Вы выбрали правильную цель в своем объекте документа. В этом случае, когда я проверяю вашу html разметку, вы обернули все разделы в основной тег.

Вот и все, я попытался получить ваш основной тег и добавить к нему eventListener, и он работает для меня. Надеюсь, это также работает для вас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...