Skip to content

Instantly share code, notes, and snippets.

@uruly
Last active August 23, 2021 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uruly/7e1c6617f7d6308856d44cfd317fc1e4 to your computer and use it in GitHub Desktop.
Save uruly/7e1c6617f7d6308856d44cfd317fc1e4 to your computer and use it in GitHub Desktop.
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