javascript - 如何在展开前将事件的 Accordion 滚动到顶部

标签 javascript jquery html css arrays

我使用 html 、 css 和 jquery 创建了一个 Accordion

每当展开 Accordion 时,我希望 Accordion 标题在展开之前滚动并位于页面的最顶部(不包括一点空间,这样它就不会覆盖我的固定导航栏)

我希望这适用于每个 Accordion ,无论其默认位置如何 (例如,页面底部的 Accordion 应该先滚动到顶部,然后再展开)

我尝试对相关的 css 类使用 scrollTop(0),但它似乎不起作用

它只需要对 Jquery 代码进行一些更改

希望有人能提供帮助

在片段中附加所有代码 (对于这个特定的示例,我在页面的最顶部放置了一个 Accordion ,在底部底部放置了一个,以便于检查某人的查询固定代码是否按预期工作很容易)

$(document).ready(function () {
  function close_accordion_section() {
    $('.accordion .accordion-section-title').removeClass('active');
    $('.accordion .accordion-section-content').slideUp(300).removeClass('open');
  }

  $('.accordion-section-title').click(function (e) {
    // Grab current anchor value
    var currentAttrValue = $(this).attr('href');

    if ($(e.target).is('.active')) {
      close_accordion_section();
    } else {
      close_accordion_section();

      // Add active class to section title
      $(this).addClass('active');
      // Open up the hidden content panel
      $('.accordion ' + currentAttrValue).slideDown(300).addClass('open')
    }

    e.preventDefault();
  });
});
/*----- Accordion -----*/

.accordion,
.accordion * {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.accordion {
  overflow: hidden;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.25);
  border-radius: 3px;
  background: #f7f7f7;
}

/*----- Section Titles -----*/

.accordion-section-title {
  width: 100%;
  padding: 15px;
  display: inline-block;
  border-bottom: 1px solid #1a1a1a;
  background: #333;
  transition: all linear 0.15s;
  /* Type */
  font-size: 1.200em;
  text-shadow: 0px 1px 0px #1a1a1a;
  color: #fff;
}

@media (hover: hover) {
  .accordion-section-title:hover {
   background: #4c4c4c;
   text-decoration: none;
   opacity: 0.5;
  }
}

.accordion-section-title.active{
  background: #4c4c4c;
  text-decoration: none;
  opacity: 0.5;
}

.accordion-section:last-child .accordion-section-title {
  border-bottom: none;
}

/*----- Section Content -----*/

.accordion-section-content {
  max-height: calc(100vh - 120px);
  overflow-y: scroll;
  padding: 15px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-1">Accordion Section #1</a>
    <div id="accordion-1" class="accordion-section-content">
      <p>Mauris interdum fringilla augue vitae tincidunt. Curabitur vitae tortor id eros euismod ultrices. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent nulla mi, rutrum ut feugiat at, vestibulum ut neque? Cras tincidunt enim vel aliquet facilisis. Duis congue ullamcorper vehicula. Proin nunc lacus, semper sit amet elit sit amet, aliquet pulvinar erat. Nunc pretium quis sapien eu rhoncus. Suspendisse ornare gravida mi, et placerat tellus tempor vitae.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</p>
    </div>
    <!--end .accordion-section-content-->
  </div>
  <!--end .accordion-section-->
</div>
<!--end .accordion-->



Body Text Starts here<br><br>
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32

<div class="accordion">
  <div class="accordion-section">
    <a class="accordion-section-title" href="#accordion-2">Accordion Section #2</a>
    <div id="accordion-2" class="accordion-section-content">
      <p>Mauris interdum fringilla augue vitae tincidunt. Curabitur vitae tortor id eros euismod ultrices. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Praesent nulla mi, rutrum ut feugiat at, vestibulum ut neque? Cras tincidunt enim vel aliquet facilisis. Duis congue ullamcorper vehicula. Proin nunc lacus, semper sit amet elit sit amet, aliquet pulvinar erat. Nunc pretium quis sapien eu rhoncus. Suspendisse ornare gravida mi, et placerat tellus tempor vitae.
What is Lorem Ipsum?
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

Where does it come from?
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</p>
    </div>
    <!--end .accordion-section-content-->
  </div>
  <!--end .accordion-section-->
</div>
<!--end .accordion-->

自 1500 年代以来使用的 Lorem Ipsum 标准 block 在下面为感兴趣的人复制。西塞罗的“de Finibus Bonorum et Malorum”中的第 1.10.32 和 1.10.33 节也以其原始形式复制,并附有 H. Rackham 1914 年翻译的英文版本。

最佳答案

使用jQuery的animate()方法添加流畅的页面滚动

替换代码

$('.accordion-section-content').scrollTop(0);

对于

$(".accordion-section a").on('click', function (event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
        // Prevent default anchor click behavior
        event.preventDefault();

        // Store hash
        var hash = this.hash;

        // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 800, function () {

            // Add hash (#) to URL when done scrolling (default click behavior)
            window.location.hash = hash;
        });
    } // End if
});

关于javascript - 如何在展开前将事件的 Accordion 滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926156/

相关文章:

javascript - 在 ASP.NET 中动态更改单选按钮选择上的表格单元格

jquery - 背景尺寸 : Cover - Firefox issue

html - 绝对定位的 h1 标题在向下滚动时向下移动

jquery - 内边框半径不起作用

jquery - 查找事件链接父级和克隆嵌套 ul

javascript - 根据字符大小指定输入字段宽度

javascript - 用于电话号码验证的正则表达式,具有最小和最大长度检查

javascript - 如何从 AJAX 响应更新大表?

javascript - 使用javascript自动链接页面上的短语

javascript - 加载javascript时如何修复流体div标签