我想通过固定菜单“ Wie zijn wij”,“ Onze missie,visie en kernwaarden”等更改背景颜色。因此,当您向下滚动并到达某个点时,背景会更改颜色。 Example
这是到目前为止我编写的代码:
function scrollIt(element) {
window.scrollTo({
'behavior': 'smooth',
'left': 0,
'top': element.offsetTop
});
}
const btn = document.querySelectorAll('.btn');
const sections = document.querySelectorAll('.section');
btn[0].addEventListener('click', () => {
scrollIt(sections[0]);
});
btn[1].addEventListener('click', () => {
scrollIt(sections[1]);
});
btn[2].addEventListener('click', () => {
scrollIt(sections[2]);
});
btn[3].addEventListener('click', () => {
scrollIt(sections[3]);
});
btn[4].addEventListener('click', () => {
scrollIt(sections[4]);
});
btn[5].addEventListener('click', () => {
scrollIt(sections[5]);
});
btn[6].addEventListener('click', () => {
scrollIt(sections[6]);
});
var header = document.getElementById("sidenav");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btn.length; i++) {
btn[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
if (current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className += " active";
});
}
@import url('https://fonts.googleapis.com/css?family=Poppins');
body {
font-family: 'Poppins', sans-serif;
}
#sidenav {
width: 200px;
position: fixed;
overflow-x: hidden;
margin-top: 10px;
margin-left: 10px;
}
.btn{
color: black;
padding: 5px 10px;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 2px;
cursor: pointer;
border: 1px solid black;
border-radius: 7px;
width: 176px;
text-align: left;
background-color: #f5f5f5;
font-weight: 300;
}
a:hover{
color: ##9ce728;
}
a:focus {
background-color: #EAB126
}
/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
background-color: #a6a8ad;
color: #fff;
}
.section {
width: 100%;
height: 100vh;
line-height: 100vh;
text-align: center;
&:nth-child(even) {
background: #eee;
}
&:nth-child(odd) {
background: #ccc;
}
}
<div id="sidenav">
<a class="btn">Wie zijn wij?</a>
<br>
<a class="btn">Onze missie, visie en kernwaarden</a>
<br>
<a class="btn">Wat zegt onze klant?</a>
<br>
<a class="btn">Onze klantcases</a>
<br>
<a class="btn">Wat zeggen professionals?</a>
<br>
<a class="btn">Nieuwsberichten</a>
<br>
<a class="btn">Onze klanten</a>
<br>
</div>
<div class="section">Pagina 1</div>
<div class="section">Pagina 2</div>
<div class="section">Pagina 3</div>
<div class="section">Pagina 4</div>
<div class="section">Pagina 5</div>
<div class="section">Pagina 6</div>
<div class="section">Pagina 7</div>
对于那些精通Java的人来说,这可能是一个简单的解决方法,但是对我而言,这是全新的。 有人可以告诉我这是怎么做的吗?
答案 0 :(得分:0)
在js下面使用来更改包含不同背景颜色的类。我在这里使用jquery
HTML
<body>
<div class='tmp'> This is a sample div </div>
</body>
JS
$(window).scroll(function() {
if (document.body.scrollTop <= 0 ){
console.log('scrolll');
$(".tmp").addClass("diffColor");
}
});
CSS
body {
height: 400px;
}
.tmp {
background: red;
height: 500px;
}
.diffColor {
background-color: blue;
}