为什么这个slideUp功能不流畅?

2024-04-17

我想实现 jQuery 的普通 JS 版本slideUp()and slideDown()功能。

我的想法是使用 CSStransition为了height属性以及使用增加/减少高度requestAnimationFrame().

我用下面的代码尝试过,并且slideDown正在按预期工作,但是slideUp并不是平滑地塌陷,而是突然消失了。

它看起来是这样的:

这里有一个jsfiddle https://jsfiddle.net/dc1r742h/5/.

  function toggleSlide(element) {
  // Check if the element is currently visible
  if (element.style.display== '' || element.style.display== 'none') {
    // If the element is not visible, slide it down
    slideDown(element);
  } else {
    // If the element is visible, slide it up
    slideUp(element);
  }
}


function slideDown(element) {

  // If the element is not visible, set the display and height properties
  if (element.style.display !== 'block') {
    element.style.display = 'block';
    element.style.height = 0;
  }
  
    // Get the height of the element's content
  const contentHeight = element.scrollHeight;

  // Set a variable to keep track of the element's height
  let currentHeight = 0;

  // Start an animation loop
  function animate() {
    // Increase the element's height by 10px
    currentHeight += 10;

    // Update the element's height
    element.style.height = `${currentHeight}px`;

    // If the element's height is less than the content height, request another animation frame
    if (currentHeight < contentHeight) {
      requestAnimationFrame(animate);
    }
  }

  // Start the animation
  animate();
}

function slideUp(element) {
  // Get the height of the element's content
  const contentHeight = element.scrollHeight;
  // Set a variable to keep track of the element's height
  let currentHeight = contentHeight;

  // Start an animation loop
  function animate() {
    // Decrease the element's height by 10px
    currentHeight -= 10;

    // Update the element's height
    element.style.height = `${currentHeight}px`;
    
    // If the element's height is greater than 0, request another animation frame
    if (currentHeight > 0) {
   
      requestAnimationFrame(animate);
    } else {
      // If the animation is complete, hide the element
      element.style.display = 'none';
    }
    
  }

  // Start the animation
  animate();
}
 .my-element {
        background-color: #ddd;
        
        transition: height 0.5s;
        overflow: hidden;
        display:none;
      }
   <button onclick="toggleSlide(document.querySelector('.my-element'))">Slide Down</button>

    <!-- Create the element that we will slide down -->
    <div class="my-element">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et tellus in quam convallis dictum. Maecenas eget odio eget arcu accumsan porttitor. Ut elementum volutpat orci, sed tincidunt ipsum dictum at. Maecenas auctor tempus diam quis gravida. Aliquam at ultricies leo. Etiam euismod, nisi ac blandit placerat, diam turpis vestibulum diam, at ultricies turpis orci at elit. Mauris auctor dictum dolor, quis pretium nisi ultricies in. Aenean sollicitudin, quam non euismod porta, enim nisl laoreet velit, vel venenatis dui dui vel lacus. Aliquam erat volutpat. Donec et elit ut ipsum elementum volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent a nisi at est eleifend ullamcorper. Aenean porta, erat ac sagittis fermentum, leo magna tincidunt lectus, ac semper risus est et diam. Suspendisse auctor ipsum quam, id porta dui dictum sed. Vivamus ac diam non elit placerat iaculis vel at velit. Aliquam vel tincidunt velit. Duis imperdiet, dolor eu placerat luctus, ipsum quam laoreet dui, non suscipit nulla tellus et arcu. Donec dictum, massa non bibendum varius, leo urna condimentum diam, nec suscipit elit turpis vel turpis. Aenean ac nunc quis nisl tempus tincidunt a eu metus.</p>
    </div>

Why is slideUp不顺利塌陷吗?


CSS 过渡是在切换动画结束之前生效的过渡。删除它可以解决问题,因为您的函数正在处理动画持续时间

function toggleSlide(element) {
  // Check if the element is currently visible
  if (element.style.display== '' || element.style.display== 'none') {
    // If the element is not visible, slide it down
    slideDown(element);
  } else {
    // If the element is visible, slide it up
    slideUp(element);
  }
}


function slideDown(element) {

  // If the element is not visible, set the display and height properties
  if (element.style.display !== 'block') {
    element.style.display = 'block';
    element.style.height = 0;
  }
  
    // Get the height of the element's content
  const contentHeight = element.scrollHeight;

  // Set a variable to keep track of the element's height
  let currentHeight = 0;

  // Start an animation loop
  function animate() {
    // Increase the element's height by 10px
    currentHeight += 10;

    // Update the element's height
    element.style.height = `${currentHeight}px`;

    // If the element's height is less than the content height, request another animation frame
    if (currentHeight < contentHeight) {
      requestAnimationFrame(animate);
    }
  }

  // Start the animation
  animate();
}

function slideUp(element) {
  // Get the height of the element's content
  const contentHeight = element.scrollHeight;
  // Set a variable to keep track of the element's height
  let currentHeight = contentHeight;

  // Start an animation loop
  function animate() {
    // Decrease the element's height by 10px
    currentHeight -= 10;

    // Update the element's height
    element.style.height = `${currentHeight}px`;
    
    // If the element's height is greater than 0, request another animation frame
    if (currentHeight > 0) {
   
      requestAnimationFrame(animate);
    } else {
      // If the animation is complete, hide the element
      element.style.display = 'none';
    }
    
  }

  // Start the animation
  animate();
}
.my-element {
        background-color: #ddd;
        /* Remove the transition */
        overflow: hidden;
        display:none;
      }
<button onclick="toggleSlide(document.querySelector('.my-element'))">Slide Down</button>

    <!-- Create the element that we will slide down -->
    <div class="my-element">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In et tellus in quam convallis dictum. Maecenas eget odio eget arcu accumsan porttitor. Ut elementum volutpat orci, sed tincidunt ipsum dictum at. Maecenas auctor tempus diam quis gravida. Aliquam at ultricies leo. Etiam euismod, nisi ac blandit placerat, diam turpis vestibulum diam, at ultricies turpis orci at elit. Mauris auctor dictum dolor, quis pretium nisi ultricies in. Aenean sollicitudin, quam non euismod porta, enim nisl laoreet velit, vel venenatis dui dui vel lacus. Aliquam erat volutpat. Donec et elit ut ipsum elementum volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent a nisi at est eleifend ullamcorper. Aenean porta, erat ac sagittis fermentum, leo magna tincidunt lectus, ac semper risus est et diam. Suspendisse auctor ipsum quam, id porta dui dictum sed. Vivamus ac diam non elit placerat iaculis vel at velit. Aliquam vel tincidunt velit. Duis imperdiet, dolor eu placerat luctus, ipsum quam laoreet dui, non suscipit nulla tellus et arcu. Donec dictum, massa non bibendum varius, leo urna condimentum diam, nec suscipit elit turpis vel turpis. Aenean ac nunc quis nisl tempus tincidunt a eu metus.</p>
    </div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么这个slideUp功能不流畅? 的相关文章

随机推荐

  • 计算函数合理性的算法/蒙特卡罗方法

    我正在编写一个程序 尝试复制本文开头讨论的算法 http www stat stanford edu cgates PERSI papers MCMCRev pdf http www stat stanford edu cgates PER
  • 我将如何使用括号表示法中的单个变量来访问深度值?

    我想知道如何执行以下操作 我有以下数据 dta fielddata text1 4B030C2E 3D53 4DF8 A3535EF377B45DE5 text2 Unlabeled 我可以使用括号符号访问它 如下所示 var result
  • Google 表格中的正则表达式“NOT”(RE2)

    我想检查单元格中是否有一个单词而不是另一个单词 在这个帖子 https stackoverflow com questions 28775466 google sheet regexreplace match everything exce
  • 删除与某个模式匹配的多个文件

    我使用 Python 和 Django 制作了一个在线画廊 我刚刚开始添加编辑功能 从旋转开始 我使用 sorl thumbnail 按需自动生成缩略图 当我编辑原始文件时 我需要清理所有缩略图 以便生成新的缩略图 每张图片有三到四个 我针
  • Swift async/await 取代了 DispatchQueue.main.async

    在新的 Swift 5 5 中使用 async await 并发机制时如何返回主线程 我应该只用 MainActor 标记函数 类吗 我还能用吗DispatchQueue main async 会是正确的吗 因为新机制不使用 GCD 并且异
  • HABTM 与强参数的关联不会在 Rails 4 中保存用户

    用户模型 has and belongs to many events 事件模型 has and belongs to many users 用户控制器 params require user permit role event ids g
  • geoIP 从 ASP.NET 查找国家/地区

    我可以从 ASP NET 页面检索客户端的 IP 地址 至少是表面上的 IP 地址 我想知道是否有可以从代码隐藏访问的免费服务 当使用 IP 查询时 该服务将返回国家 地区 不需要城市 我无法使用基于 Web http 的服务 您必须手动输
  • 如何消除SQL中的NULL字段

    我正在为 SQL Server 2008 R2 开发 TSQL 查询 我正在尝试开发此查询来识别一条记录 客户 由于其中一些值为 NULL 因此我目前正在对大多数表执行 LEFT JOINS 但 LEFT JOIN 的问题是 现在我为某些客
  • Nestjs Apollo graphql上传标量

    我正在使用 Nestjs graphql 框架 我想使用 apollo 标量上传 我已经能够在另一个不包含 Nestjs 的项目中使用标量 schema graphql App module ts注册graphql GraphQLModul
  • 如何查询Firebase Firestore参考数据类型?

    我正在使用 Firestore参考 https firebase google com docs firestore manage data data types用于存储对用户的引用的数据类型 如下面的屏幕截图所示 用户参考 用户收藏 当我
  • Angular 4 + Electron - 如何运行应用程序并观察更改(实时重新加载)

    我正在使用 Angular 4 创建一个 Electron 应用程序 我如何设置它 以便它监视任何更改并实时重新加载它 包 json name angular electron version 0 0 0 license MIT main
  • 如何将网络音频流保存到文件(c++/java)

    是否有任何库或众所周知的方法来保存音频网络流 网络广播 mp3 流 以编程方式归档 您可以使用 libvlcVLC http www videolan org vlc 项目 这wiki http wiki videolan org Libv
  • 策略模式和访客模式有什么区别?

    我很难理解这两种设计模式 您能否给我上下文信息或示例 以便我可以得到清晰的想法并能够映射两者之间的差异 Thanks The 策略模式就像一个1 many关系 当存在一种类型的对象并且我想对其应用多个操作时 我使用策略模式 例如 如果我有一
  • mojoPortal 还是 Umbraco?

    我已经寻找免费 开源 ASP NET CMS 门户系统有一段时间了 并将其分为两个不同的系统 乌姆布拉科 http umbraco org http umbraco org 魔力门户 http www mojoportal com http
  • 如何让 ASP.NET DataPager 控件在 UpdatePanel 中工作?

    我有一个顶部有参数的搜索页面 底部有一个带有结果的搜索按钮 整个内容都包含在母版页内的更新面板中 单击搜索按钮后 它会显示第一页 但是 如果您单击 DataPager 上的下一个按钮 它不会显示第二页 它显示第二页没有结果 任何帮助将不胜感
  • C++ 和 Java 中异常处理的区别?

    在Java中 如果特定的代码行导致程序崩溃 那么异常就会被捕获并且程序会继续执行 但是 在 C 中 如果我有一段代码导致程序崩溃 例如 try int x 6 int p NULL p reinterpret cast
  • 如何测试子组件是否已渲染?

    在酶中 您可以检查子组件是否存在 如下所示 expect wrapper find ChildComponent toHaveLength 1 React 测试库中的这个测试相当于什么 我找到的所有在线示例都只涵盖了寻找 dom 元素的非常
  • REST API 与 Web API

    我是构建 HTTP API 的初学者 我似乎对 REST API 和 Web API 之间的区别感到困惑 我在网上读到更多相关内容 困惑似乎越来越多 我猜菲尔丁有与此链接相同的问题http roy gbiv com untangled 20
  • 如何获取引用 postgresql 中的表的物化视图

    在 postgresql 中 借助 information schema views 表 可以通过简单的 sql 获取引用表的所有视图 但我需要一个等效的 sql 来获取引用该表的物化视图 欲查看以下作品 SELECT FROM infor
  • 为什么这个slideUp功能不流畅?

    我想实现 jQuery 的普通 JS 版本slideUp and slideDown 功能 我的想法是使用 CSStransition为了height属性以及使用增加 减少高度requestAnimationFrame 我用下面的代码尝试过