我编写了一个函数来使柱状图具有动画效果。目前这个动作是在页面加载时触发的,但我只想在到达元素时触发它,否则用户将看不到动画。
我想通过原生JavaScript实现这一点,这可行吗?
这是我的标记:
<div class="section">
section
</div>
<div class="section">
section
</div>
<div class="section">
section
</div>
<div class="section">
section
<ul class="skills__list">
<li class="skills__list-item">
<div class="bar">
<span>HTML</span>
<div class="bar__inner" data-percent="90%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>css</span>
<div class="bar__inner" data-percent="80%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>Javascript</span>
<div class="bar__inner" data-percent="60%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>UI design</span>
<div class="bar__inner" data-percent="70%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>sketch</span>
<div class="bar__inner" data-percent="50%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>Photoshop</span>
<div class="bar__inner" data-percent="80%"></div>
</div>
</li>
<li class="skills__list-item">
<div class="bar">
<span>Illustrator</span>
<div class="bar__inner" data-percent="90%"></div>
</div>
</li>
</ul>
</div>
这里是Scss代码:
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
.section {
padding: 20px;
font-size: 30px;
font-family: sans-serif;
text-transform: uppercase;
height: 400px;
&:nth-child(1){
background-color: #ddd;
}
&:nth-child(2){
background-color: #aaa;
}
&:nth-child(3){
background-color: #bbb;
}
&:nth-child(4){
background-color: #000;
}
}
.skills__list-item {
& + .skills__list-item {
margin-top: 20px;
}
}
// bar chart styles
.bar {
position: relative;
width: 100%;
height: 28px;
overflow: hidden;
background-color: blue;
span {
position: absolute;
z-index: 9;
display: flex;
align-items: center;
height: 100%;
padding: 10px;
color: #fff;
background-color: red;
}
&__inner {
display: flex;
justify-content: flex-end;
width: 0;
height: 100%;
background-color: green;
transform-origin: 0 100%;
transition: width 0.6s linear;
&::after {
content: attr(data-percent);
align-self: center;
padding-right: 20px;
color: #fff;
}
}
}
以下是JavaScript代码:
const bars = document.querySelectorAll('.bar__inner');
Array.from(bars).forEach((bar, index) => {
setTimeout(() => {
const eachBar = bar;
eachBar.style.width = bar.dataset.percent;
}, index * 400);
});
这是一个可运行的实例,Codepen。