交换后如何滚动到元素底部?

问题描述 投票:0回答:1
javascript html dom htmx
1个回答
0
投票

根据@McPherson的评论,我调整了你的代码,使其滚动。我删除了你的 Javascript 事件并用滚动修饰符替换它们,而不是

hx-swap="innerHTML"

就是现在

hx-swap="innerHTML scroll:bottom"

下面是演示滚动的交互式演示。它包括

/api/todos
的模拟端点和一些用于使滚动效果更加明显的 CSS。我试图根据按钮中的字段猜测您可能拥有哪些其他元素,并将字段重置移动到表单元素,而不是一一重置它们。

<!-- load demo environment -->
<script src="https://demo.htmx.org/demo.js"></script>

<!-- your modified code -->
<div id="todos">
  <form hx-on::after-request="this.reset()">
    <input id="field-description" type="text">
    <input id="field-amount" type="number">

    <button
            id="button"
            hx-post="/api/todos"
            hx-include="#field-description, #field-amount"
            hx-target="#todos-container"
            hx-swap="innerHTML scroll:bottom"
            >
            Add
    </button>
  </form>

  <ul id="todos-container"></ul>
</div>

<!-- styles to make the scrolling more obvious in the demo -->
<style>
  #todos-container {
    background: lightblue;
    height: 3rem;
    overflow: scroll;
    scroll-behavior: smooth;
  }
</style>

<!-- mock endpoint to render todo items -->
<template url="/api/todos">
    ${todo(this["field-description"].value, this["field-amount"].value)}
</template>
<!-- extra logic to output list of all todos as innerHTML as in the
question asker's example -->
<script>
  let todo = function() {
    todos = []
    return (desc, amt) => {
      todos.push(`<li>${desc} (${amt})`)
      return todos.join('')
    }
  }()
</script>

© www.soinside.com 2019 - 2024. All rights reserved.