我的问题出在 body
底部的 script
元素中。当您在 yScroll
函数中声明 pageTop
、menu
和 yPos
变量时该函数工作正常,但当它不是外部。如果它们在函数之外并且是全局变量,我的 function
不应该仍然能够使用它们吗?我不明白为什么当我尝试在函数外部定义变量时它不起作用。
这是代码
<!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
仅在页面加载时设置一次,并且将始终保持为 0
。
要解决此问题,请在每次调用事件处理程序时在 yScroll
函数内读取滚动位置:
<!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');
window.addEventListener('scroll', yScroll);
function yScroll() {
var yPos = window.pageYOffset;
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>
关于javascript - 为什么我的函数不能识别我的全局变量? (JavaScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065500/