JSFiddle - React, Tailwind, and code Playground
by yshrkn
HTML
<div class="window-info">
画面幅:<span class="window-width"></span><br>
画面高さ:<span class="window-height"></span><br>
スクロール位置:<span class="scroll-position"></span><br>
</div>
<section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section><section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section><section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section><section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section><section>
<h2>headding</h2>
<p>text</p>
</section>
<section>
<h2>headding</h2>
<p>text</p>
</section>
<a href="#" class="toTop">トップへ戻る</a>
CSS
.window-info {
position: fixed;
text-outline: 0;
right: 0;
background: rgba(0,0,0,0.1);
}
.toTop {
display: none;
}
JavaScript
(function() {
var windowHeight;
var windowWidth;
var scrollPosition;
var $window = $(window);
var $toTop = $(".toTop");
var $windowWidthDisplay = $(".window-width");
var $windowHeightDisplay = $(".window-height");
var $scrollPositionDisplay = $(".scroll-position");
/* 画面サイズに関するプロパティのセット */
function setWindowPropertys() {
windowHeight = $window.height();
windowWidth = $window.width();
console.log(windowHeight);
}
/* イベントハンドラの登録 */
function addEventListeners() {
$window.on("scroll", setWindowPropertys);
}
function init() {
$window.resize(setWindowPropertys);
$window.on("scroll", function() {
//ウィンドウの情報をhtml側に表示
$windowWidthDisplay.html(windowWidth);
$windowHeightDisplay.html(windowHeight);
scrollPosition = $window.scrollTop();
$scrollPositionDisplay.html(scrollPosition);
if (scrollPosition >= 300) {
$toTop.css({
"display": "block",
"top": windowHeight - 100
});
} else {
$toTop.css({"display": "none"});
}
});
}
init();
}());