首页 > 解决方案 > 如何在动画后恢复 div 的宽度?

问题描述

这是我正在尝试做的事情:

position:sticky div 中有一个矩形 (id=mysquare)。滚动一点后,mysquare 的宽度应该使用 jquery 的动画缩小。然后,当向上滚动时,mysquare 应该会立即恢复到原来的宽度。

问题:

动画位工作正常。不起作用的是恢复到 mysquare 的原始宽度。当您在 mysquare 缩小到 100 像素后向上滚动时,它保持不变(理论上应该回到 150 像素)。

var headheight = $(".myheading").height();

$(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > headheight) {
      //if scrolled past myheading
      //Gradually change the width of the square to 100px, from 150px
      $("#mysquare").animate({
        width: "100px",
      }, 1500);

    }
    if ($(this).scrollTop() < headheight) {
      //If not scrolled past myheading
      //Keep the square big
      $("#mysquare").width("150px");
    }
  })
});
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background-color: yellow;
  padding: 10px;
  font-size: 20px;
}

#mysquare {
  height: 50px;
  background-color: #555;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>

  <div class="myheading" style="height: 50px;"></div>
  <div class="sticky">Hello
    <div id="mysquare" style="width 150px;">

    </div>
  </div>

  <main style="height:500px;"></main>
</body>

</html>

一个 JSFiddle:https ://jsfiddle.net/82n16x07/7/

附带说明一下,mysquare 在首次加载时似乎占据了屏幕的整个宽度。对此的任何帮助也将不胜感激。

标签: javascripthtmljquerycss

解决方案


您的初始宽度问题是由不正确的style指令引起的,缺少冒号:

<div id="mysquare" style="width 150px;">

应该:

<div id="mysquare" style="width: 150px;">

主要问题是由于animate()在滚动条件为真时重复调用该函数,并且这些函数调用堆积起来。如果您等待足够长的时间,它们就会清除,并且盒子会恢复到正常大小。

要解决此问题,您可以添加一个shrunk标志来确定框是否缩小,并检查此标志以确定是否发出新animate()调用。

var headheight = $(".myheading").height();
var shrunk=false;
$(function() {
  $(window).scroll(function() {
  
    if ($(this).scrollTop() > headheight && !shrunk) {
      //if scrolled past myheading
      //Gradually change the width of the square back to the size of the new image
           shrunk=true;
      $("#mysquare").animate({
        width: "100px",
      }, 1500);

    }
    if ($(this).scrollTop() < headheight) {
      //If not scrolled past myheading
      //Keep the square big
      shrunk=false;
      $("#mysquare").width("150px");
     }
  })
});
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background-color: yellow;
  padding: 10px;
  font-size: 20px;
}

#mysquare {
  height: 50px;
width:150px;
  background-color: #555;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
</head>

<body>

  <div class="myheading" style="height: 50px;"></div>
  <div class="sticky">Hello
    <div id="mysquare" style="width: 150px;">

    </div>
  </div>

  <main style="height:500px;"></main>
</body>

</html>


推荐阅读