この前作った実行タイミングをスクロール料の数値を固定された方法だと、画面の高さの問題でマルチデバイスに対応てきてなさそうだした。
jqueryでスクロール量を取得するパララックスサイトコーディング
微調整するのもめんどくさかったりと保守性の問題点もあったので、それを解決するために指定の要素が画面内に現れたら実行されるjqueryのサンプルを作ってみました。
さらにCSS3のアニメーションでパララックスが楽に作れる
jqueryで動きをつけるより、簡単でスムーズな動きを作ることができるのが、CSS3のanimationプロパティです。CSSの方が得意だし、jqueryをガチャガチャやるよりこっちの方が断然簡単だった。
animationプロパティを知らなかったわけじゃないけど、CSSでパララックス用のアニメーションを作るという概念がなかったから、人に言われて初めて気がつきました。
あらかじめ作っておいたanimationのクラス等を付与するなり、入れ替えるなりするだけ。
スクロールの実行タイミングよCSS3アニメーションを細かく説明
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function () {
//スクロール実行中の処理
$(window).scroll(function () {
//#action要素のスクロール量を代入
var obj_t_pos = $("#action").offset().top;
//画面のスクロール量と#actionのスクロール量を計算して実行タイミングを代入
var scr_count = $(document).scrollTop() + (window.innerHeight / 1.2);
//#action要素が現れたら実行
if (scr_count > obj_t_pos) {
//classの書き換え anime1が動き出す
$("#fixed").removeClass("anime2").addClass("anime1");
} else {
//classの書き換え anime2が動き出す
$("#fixed").removeClass("anime1").addClass("anime2");
}
});
});
</script>
<style>
/* 簡易リセット */
* {
margin: 0;
padding: 0;
}
body {
margin: auto;
/* 仮の高さ */
position: relative;
height: 3000px;
width: 768px;
}
#fixed {
margin: -400px 0 0 -200px;
display: inline-block;
position: fixed;
top: 0;
left: 50%;
width: 400px;
height: 400px;
vertical-align: middle;
color: #FFF;
background: #000;
text-align: center;
}
#fixed:before {
display: inline-block;
height: 100%;
width: 0;
content: "";
vertical-align: middle;
}
#fixed span {
display: inline-block;
vertical-align: middle;
}
#action {
position: absolute;
bottom: 25%;
}
/*アニメーション設定*/
#fixed.anime1 {
animation: anime1 1.5s both;
}
#fixed.anime2 {
animation: anime2 1.5s both;
}
/*始まりのアニメーション設定*/
@keyframes anime1 {
0% {
top: 0;
}
100% {
margin-top: -200px;
top: 50%;
}
}
/*戻りのアニメーション設定*/
@keyframes anime2 {
0% {
margin-top: -200px;
top: 50%;
}
100% {
top: 0;
}
}
</style>
</head>
<body>
<div id="fixed"> <span id="scroll">TEST</span> </div>
<p id="action">見えたら実行</p>
</body>
</html>
要素が画面下の20%位置に来たら、発火するjqueryです。派手なLPなど動きのあるページを作りたい時に、このjqueryとCSS3のアニメーションがなり便利に使えそうです。