javascript - 如何在动画后恢复 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 在首次加载时似乎占据了屏幕的整个宽度。对此的任何帮助也将不胜感激。
解决方案
您的初始宽度问题是由不正确的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>
推荐阅读
- google-drive-api - fpdf 输出,是否可以将我的输出保存到特定帐户的谷歌驱动器?
- reactjs - React - 使用带有 useState Hook 的回调函数
- php - 将一组 URL 限制为最大值。每个子域+域 3 个项目
- django - Django 教程,如何发送多个参数?
- python - 在python中使用类方法设置类属性
- sql - INNER JOIN - 选择多于一行错误的结果
- r - 在编织 R 降价时尝试使用 tidyselect 函数创建新变量时 mutate_at 出错
- node.js - 使用 PM2 时如何仅在一个实例中运行代码?
- r - 如何在 R 中的数据操作之前和之后使用 ggplot 为 ggarrange 制作“持久”图
- sql - 从 PLC 到 PC 写入 SQL 表时数据损坏