スクロールに応じてクラス付与
by yshrkn
HTML
<div class="scrollValue">0</div>
<div class="animStartValue">0</div>
<div class="targetElement anim-move-to-top"></div>
<div class="targetElement anim-move-to-right"></div>
SCSS
body { height: 10000px; }
.targetElement {
width: 50px;
height: 50px;
background-color: #000;
opacity: 1;
transform: translate(0);
transition: all 0.5s ease-out;
}
.scrollValue,
.animStartValue {
position: fixed;
top: 0;
right: 0;
width: 40%;
background-color: #333;
color: #fff;
text-align: right;
padding-right: 20px;
}
.animStartValue {
top: 20px;
}
/* アニメーション */
.anim-move-to-top {
transform: translateY(500px);
opacity: 0.5;
}
.anim-move-to-right {
transform: translateX(500px);
opacity: 0.5;
}
JavaScript
$(function () {
var jqueryMap = {
$window: $(window),
$scrollValue: $(".scrollValue"),
$animStartValue: $(".animStartValue"),
$targetElement: $(".targetElement")
};
var setMap = {
adjustAnimStartPosition: 0, //アニメーションクラスをウィンドウの高さのどの位置で取るかを調整する
animClassRegex: /anim-.*/g
};
var stateMap = {
animStartPosition: 0 //ウィンドウの高さの最下部の位置
};
// //transitionに対応しているかどうか
// function xxx() {}
function addEventListeners() {
console.log("targetElement:", jqueryMap.$targetElement);
jqueryMap.$window.on("load scroll resize", function() {
stateMap.animStartPosition = jqueryMap.$window.scrollTop()
+ jqueryMap.$window.height()
+ (setMap.adjustAnimStartPosition);
//データ値の出力用
jqueryMap.$scrollValue.html("スクロール量:" + jqueryMap.$window.scrollTop());
jqueryMap.$animStartValue.html("アニメスタート位置:" + stateMap.animStartPosition);
console.log("jqueryMap.$targetElement.offset().top:", jqueryMap.$targetElement.offset().top);
jqueryMap.$targetElement.each(function() {
console.log("$(this).offset().top:", $(this).offset().top);
if (stateMap.animStartPosition >= $(this).offset().top) {
$(this).removeClass(function(index, className) {
// anim-で
return (className.match(setMap.animClassRegex) || []).join(" ");
});
}
});
});
}
//initialize
(function() {
//stateMap設定
addEventListeners();
}());
}());