将手风琴选项卡滑动到浏览器顶部

时间:2013-12-04 05:20:40

标签: javascript jquery css accordion

我有一个非常冗长的手风琴菜单。因此,当打开手风琴内容时,我需要实现幻灯片效果。

目前,如果您打开前两个菜单项,则最后一项显示视口下方的内容,因此我需要为手风琴菜单项启用上滑效果。

这是我的代码

$(document).ready(function () {
    //Accordion
    $(".menu_body").hide();
    //toggle the componenet with class menu_body
    $(".menu_head").click(function(){
        $(this).next(".menu_body").slideToggle(400); 
        var plusmin;
        plusmin = $(this).children(".plusminus").text();

        $(this).children("span.down-arrow").toggleClass("up-arrow");        
    });

});

DEMO

解释

看到会有N个具有很长表数据的手风琴菜单项。它应该允许我们打开多个标签。

目前它工作正常,但问题是当你点击页面底部的菜单项时,它会显示内容,所以除非你手动向下滚动,否则你将无法看到它。

这就是为什么我需要菜单自动滑动滚动到浏览器的顶部,以便一目了然地看到内容。

3 个答案:

答案 0 :(得分:1)

我会计算点击的按钮offset并将整个页面滚动到该位置 减去一些像素(100)只是为了美丽:

<强> DEMO

$(function () {

    //Accordion
    $(".menu_body").hide();
    //toggle the componenet with class menu_body
    $(".menu_head").click(function(){
        var thisPOsTop = $(this).offset().top - 100;
        $(this).next(".menu_body").slideToggle(400); 
        var plusmin = $(this).find(".plusminus").text();        
        $(this).find("span.down-arrow").toggleClass("up-arrow");
      $('html, body').stop().animate({scrollTop: thisPOsTop});
    });

});

答案 1 :(得分:0)

这是我更新的 jsbin ,效果很好。 代码如下:

$(".menu_head").click(function(){

 $(this).next(".menu_body").slideToggle(400); 
    var plusmin;
    plusmin = $(this).children(".plusminus").text();

    $(this).children("span.down-arrow").toggleClass("up-arrow");

  var scrollvalue = $(this).offset().top;
  console.log(scrollvalue);
  setTimeout(function(){
  $(window).scrollTop( scrollvalue );
  },500);

});

答案 2 :(得分:0)

尝试自动滚动到特定元素怎么样?选择手风琴元素时,此“方法”可能会触发。

$('html, body').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);

上面的代码将在2秒(2000毫秒)内完成动画,但您可以将其更改为任何内容。

This JS Bin 似乎正是您正在寻找的。

$('.menu_head').click(function() {
    $('html, body').animate( { scrollTop:$(this).offset().top }, 400);
});
相关问题