私の問題は、body
の下部にあるscript
要素にあります。 pageTop
,menu
およびyPos
という変数をyScroll
関数内に宣言すると機能は正常に動作しますが、外に出ているときは機能しません。それらが関数の外にあり、グローバル変数である場合、私のfunction
はまだそれらを使用できないはずですか?なぜ私は関数の外で変数を定義しようとすると動作しないのか分かりません。私の関数がグローバル変数を認識しないのはなぜですか? (JavaScript)
はここ
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0px;
text-align: center;
}
#pagetop {
position: fixed;
top: 0px;
width: 100%;
height: 120px;
background: #06C;
color: #FFF;
font-size: 23px;
padding-top: 50px;
transition: height 0.3s linear 0s, padding 0.3s linear 0s;
overflow: hidden;
}
#pagetop > #menu {
position: absolute;
bottom: 0px;
width: 100%;
background: #004A95;
height: 50px;
transition: height 0.3s linear 0s;
}
#wrapper {
margin-top: 230px;
}
</style>
</head>
<body>
<div id="pagetop">
Header
<div id="menu">Menu system</div>
</div>
<div id="wrapper">
<script>
for(i = 0; i < 40; i++)
{
document.write("<h2>dummy page content</h2>")
}
</script>
</div>
<script>
var pagetop = document.getElementById('pagetop');
var menu = document.getElementById('menu');
var yPos = window.pageYOffset;
window.addEventListener('scroll', yScroll);
function yScroll() {
if (yPos > 150) {
pagetop.style.height = '36px';
pagetop.style.paddingTop = '8px';
menu.style.height = '0px';
}
else {
pagetop.style.height = '120px';
pagetop.style.paddingTop = '50px';
menu.style.height = '50px';
}
}
</script>
</body>
</html>
みんなありがとう、私はそれがYPOS変数を持つものだった考え出し。 – alex