Last active
August 23, 2021 12:35
-
-
Save uruly/7e1c6617f7d6308856d44cfd317fc1e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const defaultColor = 'rgb(255, 255, 0)'; | |
const stopColor = 'rgb(37, 37, 37)'; | |
/** | |
* Scroll | |
*/ | |
window.onscroll = scrollWindow; | |
/** | |
* スクロールされている間呼ばれる | |
*/ | |
function scrollWindow() { | |
// 条件 | |
var items = document.querySelectorAll('.stop'); | |
items.forEach( function(item){ | |
var backgroundColor = item.style.backgroundColor; | |
var inScreen = containsTargetPosition(item); | |
if ( inScreen && !(backgroundColor == stopColor) ){ | |
item.style.backgroundColor = stopColor; | |
stopScroll(); | |
} else if (!inScreen && backgroundColor == stopColor ) { | |
item.style.backgroundColor = defaultColor; | |
} | |
}); | |
} | |
/** | |
* スクロールを止める | |
*/ | |
function stopScroll() { | |
// 現在のスクロール量 | |
var scrollOffsetY = window.pageYOffset; | |
window.scrollTo(0,scrollOffsetY); | |
} | |
/** | |
* 要素が指定した範囲にあるかどうか | |
* @param {Element} item | |
* @return {Booelan} | |
*/ | |
function containsTargetPosition(item) { | |
var screenHeight = window.innerHeight; | |
var itemBottomY = item.getBoundingClientRect().bottom; | |
// 画面topからどれだけか | |
var targetPositionY = screenHeight / 2; | |
// 数値が小さいとスクロール時に無視されて止まらない可能性がある | |
var offset = 20; | |
if (itemBottomY >= targetPositionY - offset && itemBottomY <= targetPositionY + offset) { | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment