Accordion:自动滚动到窗格内容的顶部

时间:2018-01-19 15:39:34

标签: javascript accordion

当使用带有大窗格的手风琴时,选择一个窗格会将您带到底部内容,并将最常见的内容从屏幕的可见性中删除。每次选择窗格时强制用户向上滚动。

选择窗格时是否可以自动滚动到窗格内容的顶部?

此处有手风琴:https://jsfiddle.net/4hqv4eao/4/

require([
    "dijit/layout/AccordionContainer",
    "dijit/layout/ContentPane",
    "dojo/ready"
  ],
  function(AccordionContainer, ContentPane, ready) {

    ready(function() {

      var acc = new AccordionContainer({}, "accordion");

      acc.addChild(new ContentPane({
        title: "Title 1",
      }, "pane1"));

      acc.addChild(new ContentPane({
        title: "Title 2",
      }, "pane2"));

      acc.addChild(new ContentPane({
        title: "Title 3",
      }, "pane3"));      

      acc.addChild(new ContentPane({
        title: "Title 4",
      }, "pane4"));        

      acc.startup();
    });

  });

1 个答案:

答案 0 :(得分:1)

使用每个窗格的点击功能(我使用了for loopclassName dijitAccordionInnerContainer),你可以获得手风琴y位置(我使用here中的函数来获得确切的结果y positon)并使用javascripts scrollBy method

这里是获得确切位置的功能(感谢kirupa):

// Helper function to get an element's exact position
function getPosition(el) {
  var xPos = 0;
  var yPos = 0;

  while (el) {
    if (el.tagName == "BODY") {
      // deal with browser quirks with body/window/document and page scroll
      var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
      var yScroll = el.scrollTop || document.documentElement.scrollTop;

      xPos += (el.offsetLeft - xScroll + el.clientLeft);
      yPos += (el.offsetTop - yScroll + el.clientTop);
    } else {
      // for all other non-BODY elements
      xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
      yPos += (el.offsetTop - el.scrollTop + el.clientTop);
    }

    el = el.offsetParent;
  }
  return {
    x: xPos,
    y: yPos
  };
}

这里是我添加的代码,滚动到手风琴的顶部:

var panes;
var pane;
panes = document.getElementsByClassName('dijitAccordionInnerContainer');

for (var i = 0; i < panes.length; i++) {
  panes[i].addEventListener('click', function(e) {
    pane = this;
    setTimeout(function() {
      window.scrollBy(0, getPosition(pane).y);
    }, 200);
  });
}

我使用了setTimeout功能,因此手风琴会在获得它之前完成更新(可能有更好的方法)。

这里是updated fiddler