【问题标题】:Javascript Image Width on Scrolldown向下滚动时的Javascript图像宽度
【发布时间】:2020-08-09 08:40:31
【问题描述】:

我对 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";
  }
}

【问题讨论】:

    标签: javascript image width scrolltop


    【解决方案1】:

    您的 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";
      }
    }
    

    【讨论】:

    • 聪明!这现在工作得很好。非常感谢!
    【解决方案2】:

    您需要设置一个eventListener,在用户滚动滚轮时调用scrollFunction
    一个捷径是将&lt;body&gt; 更改为&lt;body onscroll="scrollFunction()"&gt;

    您还可以在 javascript 中设置事件监听器:

    window.addEventListener("scroll", function(e) {
      scrollFunction();
    }
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多