React
by blueseal
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/4.4.0/styled-components.min.js"></script>
<div id="app"></div>
CSS
body {
background: lightgray;
height: 5000px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
const StyledBody = window.styled.div`
background: lightgray;
height: 5000px;
`;
const StyledText = window.styled.h4`
text-align: center;
width: 250px;
margin: auto;
line-height: 40px;
`;
const StyledHeader = window.styled.div`
background-color: ${props => props.color};
width: 100%;
height: auto;
position: fixed;
top: 0;
left: 0;
right: 0px;
padding: 0;
z-index: 10000;
transition: all 1s ease-in-out;
`;
const TodoApp = () => {
const [color, setColor] = React.useState("rgba(17, 42, 107, 0.7)");
const handleScroll = React.useCallback((event) => {
let scrollTop = window.scrollY;
//console.log(scrollTop ); //1,2,...100,...200...etc (in px)
if (scrollTop >= 20 && scrollTop < 50) {
setColor("yellow");
}
if (scrollTop >= 50 && scrollTop < 90) {
setColor("red");
}
if (scrollTop >= 90 && scrollTop < 120) {
setColor("green");
}
if (scrollTop >= 120 && scrollTop < 150) {
setColor("blue");
}
if (scrollTop >= 150 && scrollTop < 180) {
setColor("violet");
}
if (scrollTop >= 180 && scrollTop < 210) {
setColor("purple");
}
});
React.useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll, false);
};
}, []);
return (
<StyledBody>
<StyledHeader color={color}>
<StyledText>My background color changes</StyledText>
</StyledHeader>
</StyledBody>
);
};
ReactDOM.render(<TodoApp />, document.querySelector("#app"))