2016-11-18 5 views
0

У меня возникли проблемы с изменением цвета моего заголовка от прозрачного до цветного при прокрутке. Я не могу использовать jQuery для этого, так как это школьное задание и регулярное JS - это требование.JavaScript для изменения цвета заголовка при прокрутке

Так что у меня этот код

var header = document.getElementById('header'); 
 
window.onscroll = function() { 
 
    "use strict"; 
 
    if (document.body.scrollTop >= 200) { 
 
     header.classList.add("header-colored"); 
 
     header.classList.remove("header-transparent"); 
 
    } 
 
    else { 
 
     header.classList.add("header-transparent"); 
 
     header.classList.remove("header-colored"); 
 
    } 
 
};
#header { 
 
    position: fixed; 
 
    height: 100px; 
 
    width: 100%; 
 
} 
 

 
#header-colored { 
 
    background-color: black; 
 
    position: fixed; 
 
    height: 100px; 
 
    width: 100%; 
 
}
<header id="header-transparent"> 
 
    <ul id="navbar"> 
 
    <li>home</li> 
 
    <li>business</li> 
 
    <li>technical</li> 
 
    <li>about us</li> 
 
    </ul> 
 
    </header> 
 

 
<header id="header-colored"> 
 
    <ul id="navbar"> 
 
    <li>home</li> 
 
    <li>business</li> 
 
    <li>technical</li> 
 
    <li>about us</li> 
 
    </ul> 
 
    </header>

И я задаюсь вопросом, куда я иду неправильно. Имейте в виду, что у меня мало опыта работы с JS, поэтому, я думаю, у меня есть хотя бы одна ошибка в скрипте.

Я также не уверен, как это сделать в файле HTML. Для начала у меня был только один заголовок, но я решил, что мне нужно как минимум два для работы JS (прозрачный и цветной).

Любой вход? :)

Редактировать: Чтобы быть ясным, что не работает, заголовок не меняет цвет при прокрутке. Он просто черный (цветная видимая за прозрачной).

+1

Для того, чтобы сказать, где вы могли бы идти неправильно, требует, чтобы мы знали, что именно происходит не так, что не работает? Пожалуйста, прочитайте «* [ask] *» рекомендации, а затем отредактируйте свой вопрос. –

+0

Кроме того, ваш пример немного шикарный, поскольку он просто добавляет два '

' -tags, не предоставляет нам фактическую прокручиваемую страницу, чтобы мы могли видеть, что происходит и т. Д. – junkfoodjunkie

+0

Извините, это мой первый раз размещение здесь. Я понял, что два тега 'header' будут плохой идеей. Изменит его. Сейчас у меня нет прокручиваемой страницы, так как у меня есть другие проблемы, которые я пытаюсь выяснить. Спасибо, что! – r4tchet

ответ

0

В основном вы допустили несколько ошибок, как показано ниже.

  1. Я изменил идентификатор заголовка в header который относится то же самое в CSS и добавил класс по умолчанию для заголовка «Заголовок прозрачных»
  2. Я изменил селектор в качестве имени класса .header-colored в CSS , который относится идентификатор, как #header-colored перед тем
  3. Я добавил еще один CSS .header-transparent с прозрачным цветом фона
  4. И, наконец, установить класс с header.className = 'header-colored' вместо вашего header.classList.add()

Я сделал это с одним заголовком и прокомментировал другой.

Работа образца: Вы должны иметь скроллбар, чтобы проверить это

var header = document.getElementById('header'); 
 
window.onscroll = function() { 
 
    "use strict"; 
 
    if (document.body.scrollTop >= 200) { 
 
     header.className = 'header-colored'; 
 
    } 
 
    else { 
 
     header.className = 'header-transparent'; 
 
    } 
 
};
#header { 
 
    position: fixed; 
 
    height: 100px; 
 
    width: 100%; 
 
} 
 

 
.header-transparent { 
 
    background-color: transparent; 
 
} 
 

 
.header-colored { 
 
    background-color: black; 
 
}
<header id="header" class="header-transparent"> 
 
    <ul id="navbar"> 
 
    <li>home</li> 
 
    <li>business</li> 
 
    <li>technical</li> 
 
    <li>about us</li> 
 
    </ul> 
 
    </header> 
 

 
<!--<header id="header-colored"> 
 
    <ul id="navbar"> 
 
    <li>home</li> 
 
    <li>business</li> 
 
    <li>technical</li> 
 
    <li>about us</li> 
 
    </ul> 
 
    </header>--> 
 
<div> 
 
    More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content More content 
 
</div>

+0

Спасибо, парень, это сработало чудеса. Я также понял, что я сделал не так, поэтому спасибо за это! – r4tchet

+0

Да, я обновил его с содержанием, чтобы увидеть это в действии здесь – Aruna

+0

У меня также есть другой вопрос, но я думаю, что здесь слишком сложно спросить. Я пытаюсь найти способ застрелить вас пополудни, но мне кажется, что это невозможно? – r4tchet

0

var header = document.getElementById('header'); 
 
window.onscroll = function() { 
 
    "use strict"; 
 
    if (document.body.scrollTop >= 200) { 
 
     header.classList.add("header-colored"); 
 
    } 
 
    else { 
 
     header.classList.add("header-transparent"); 
 
    } 
 
};
#header { 
 
    position: fixed; 
 
    height: 100px; 
 
    width: 100%; 
 
} 
 

 
.header-colored { 
 
    background-color: black; 
 
    position: fixed; 
 
    height: 100px; 
 
    width: 100%; 
 
} 
 

 
p { 
 
    max-width: 10em; 
 
    }
<header id="header"> 
 
    <ul id="navbar"> 
 
    <li>home</li> 
 
    <li>business</li> 
 
    <li>technical</li> 
 
    <li>about us</li> 
 
    </ul> 
 
    </header> 
 
<p>1914 translation by H. Rackham 
 

 
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" 
 
Section 1.10.33 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC 
 

 
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." 
 
1914 translation by H. Rackham 
 

 
"On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."</p>

Ну, во-первых, вам не нужно ничего с ID header - у вас есть <header> с id="header-transparent" - так что либо изменить getElementById('header') к getElementByTagName('header') или изменить идентификатор в первом до header-transparent.

Во-вторых, вы назначили идентификаторы, а не классы, как в HTML, так и в CSS, но вы пытаетесь добавить материал в классы. Это необходимо изменить.

+0

спасибо. Я изменил на 'getElementByTagName', и я также изменил идентификаторы на классы. Теперь я получаю сообщение об ошибке «Не могу прочитать свойство« добавить »неопределенного в window.onscroll». Вы знаете, что могло бы вызвать это? – r4tchet

+0

См. Мой обновленный ответ. Это не совсем полно, но он добавляет классы. Я вернулся к использованию ID, кстати. – junkfoodjunkie

Смежные вопросы