我是JavaScript的新手,老实说我有一个可靠的攻击计划,可以在从顶部滚动10像素后缩小徽标。目的是使徽标(通常宽度为400像素)从顶部向下滚动时变小(至100像素)。
任何人都可以帮助我了解为什么此代码未返回任何视觉响应吗?
这里是HTML标记:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="normalize.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<!--<div id="header">Header</div>-->
<div id="header">
<img id="header-image" src="logo-mockup.png">
</div>
<p>THIS IS ALL JUST FILLER TEXT RIGHT NOW.</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
CSS:
#header {
background-color: #f1f1f1; /* Grey background */
padding: 30px 0px; /* Some padding */
color: black;
text-align: center; /* Centered text */
font-size: 90px; /* Big font size */
font-weight: bold;
position: fixed; /* Fixed position - sit on top of the page */
top: 0;
width: 100%; /* Full width */
height:90px;
transition: 0.2s; /* Add a transition effect (when scrolling - and font size is decreased) */
}
#header-image {
padding: 0px 10px; /* Some padding */
text-align: center;
top: 0;
transition: 0.2s; /* Add a transition effect (when scrolling - and font size is decreased) */
}
p {
margin:300px;
}
和JS:
function scrollFunction() {
if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
document.getElementById("header-image").style.width = "100";
} else {
document.getElementById("header-image").style.width = "400";
}
}
您需要设置一个eventListener
,只要用户滚动滚轮,它就会调用scrollFunction
。一个捷径就是将<body>
更改为<body onscroll="scrollFunction()">
。您还可以在javascript中设置事件监听器:
window.addEventListener("scroll", function(e) {
scrollFunction();
}
您的scrollFunction()从未被调用。您应该为窗口滚动添加事件监听器,并记得在最后添加用于设置宽度的单位-在您的情况下为'px'。
window.onscroll = function() {
if (document.body.scrollTop > 10 || document.documentElement.scrollTop > 10) {
document.getElementById("header").style.width = "100px";
} else {
document.getElementById("header").style.width = "400px";
}
}