【WEB制作】 スクロールに応じて固定 サラリーマン投資家のFIREへの旅路 第84夜
本日は、ポートフォリオ制作の続きです。
こんな感じのを作ります!
スクロール位置に応じて、見出しを固定したい!
【要素の固定】
以前に、ヘッダーの固定で使ったのと、同じく
一定の位置までスクロールしたら、fixed というクラスをつけて
固定するっていう流れです。
「About」部分を例に見ていきましょう!
【html】
HTML
<!--About---------------------------------------------->
<section class="about">
<h1 class="scrollReveal about-title">About</h1>
<div class="about-container scrollReveal-title">
<p class="about-container-p scrollReveal-delay">abcdefgabcdefgabcdefgabcdefgabcdefg</p>
<img src="img/about-img.jpg" alt="about-img" >
</div>
</section>
【SCSS】
h1 タグに、about-titleっていうクラスをつけています!
SCSS
/*About ---------------------------------------------*/
.about{
width: 100%;
padding-top: 100px;
padding-bottom: 220px;
margin-top: 700px;
background-color: rgba($color: #928080, $alpha: .9);
.about-title{
width: 100px;
transition: .5s;
margin-left: 5%;
padding: 0 0 0 0;
background-color: none;
}
.about-container{
position: relative;
padding-top: 200px;
width: 100%;
margin: 100px auto;
text-align: right;
img{
width: 80%;
}
p.about-container-p{
position: absolute;
top: 50%;
left: 13%;
text-align: left;
width: 30%;
padding: 5%;
font-size: 1.5em;
letter-spacing: .5em;
overflow-wrap: break-word;
color: white;
background-color: rgba($color: #3f3f3f, $alpha: .6);
}
}
}
.about-title.fixed{
position: fixed;
color: white;
z-index: 1000;
padding: 2% 0 0 3%;
background-color: #6588a8;
}
.about-title.fadeOut{
position: fixed;
padding: 0 ;
color: rgba($color: #ada2a2, $alpha: 0);
}
h1につけた、about-title の SCSSと
↓ このコードで、about-title に fixed というclassが付いた時の
SCSS が書かれています!
【jQuery】
jQuery
//セクションタイトル固定 about
$(window).scroll(function(){
if ($(window).scrollTop() < 800) {
$('.about-title').removeClass('fixed');
}
if ($(window).scrollTop() > 800) {
$('.about-title').addClass('fixed');
$('.about-title').css({"top":"50px"});
}
if ($(window).scrollTop() < 1600) {
$('.about-title').removeClass('fadeOut');
}
if ($(window).scrollTop() > 1800) {
$('.about-title').removeClass('fixed');
$('.about-title').addClass('fadeOut');
}
});
↑ このjQueryのコードは、
if ($(window).scrollTop() < 800) {
$('.about-title').removeClass('fixed');
}
・・・もし、Topから見てスクロール位置が、800未満なら、
about-title のクラスの要素から、fixed というクラスを外す
という意味。
二つ目の塊は、
if ($(window).scrollTop() > 800) {
$('.about-title').addClass('fixed');
$('.about-title').css({"top":"50px"});
}
・・・もし、Topから見て、スクロール位置が800以上なら
about-title のクラス要素に、add(追加) class(クラス) fixed というクラスを
付ける。
about-title のクラス要素の、cssをいじる、その内容は、
"top" (上から)
"50px" (50pxの位置に移動)
その下の、二つの塊は、1800の位置までスクロールしたら、
fadeOutというクラスをabout-title のクラス要素につける
1600の位置までスクロールしたら、about-titleからクラス fadeOutを外す。
fixedも外す。
要するに、いい感じの位置まできたら、クラスを付けたり外したりして
その位置で行いたいアニメーションをSCSSで装飾してるっていうことです!
【まとめ】
アニメーションというほどでもないけども、
CSSでの動きの付け方の考え方として、
普通の時のCSSと
変化が加わった(クラスが付与された、クリックされた)ときの
CSSを書く。
こんなイメージですね!
変化を加えるのが、今回は、jQueryでした。
今回は、新しいクラスを付与したり、cssをjQueryで
変更したりしました。
【レスポンシブ】
今日載せたコーデは、未完成です!
画面を縮めると、いい感じの位置で、fixedされない!
これは、トップの画像の高さの指定を調整する必要があります。
後日調整して参ります!
この記事が気に入ったらサポートをしてみませんか?