You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Accordion组件:选中面板时如何实现自动滚动至内容顶部

Fix: Auto-scroll to Top of Selected Accordion Panel in Dijit

Got it, this is a common quirk when using Dijit's AccordionContainer with large content panels—browser auto-scroll behavior can yank you to the bottom of the panel right after opening it, which is super annoying. Luckily, we can fix this by adding a small bit of code to force the scroll position to the top of the selected panel.

Here's how to adjust your existing code:

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", 
      content: "Your large panel content here..."
    }, "pane1")); 
    acc.addChild(new ContentPane({ 
      title: "Title 2", 
      content: "More lengthy content that was causing scroll issues..."
    }, "pane2")); 
    acc.addChild(new ContentPane({ 
      title: "Title 3", 
      content: "Even more content to test the scroll fix..."
    }, "pane3")); 
    acc.addChild(new ContentPane({ 
      title: "Title 4", 
      content: "Huge content block that would normally jump to bottom..."
    }, "pane4")); 

    // Add this event listener to handle scroll on panel selection
    acc.on("select", function(selectedPane) {
      // Scroll the top of the selected panel into view
      selectedPane.domNode.scrollIntoView({
        block: "start", // Ensures the top edge of the panel aligns with the viewport
        behavior: "smooth" // Optional: adds smooth scrolling animation (remove for instant jump)
      });
    });

    acc.startup(); 
  }); 
});

Key Details:

  • We’re using the AccordionContainer's select event, which triggers right when a panel is activated.
  • The native scrollIntoView() browser API lets us explicitly control the panel’s position in the viewport. Setting block: "start" guarantees the top of the panel is visible.
  • The behavior: "smooth" option is a nice user experience touch, but you can omit it if you prefer an immediate scroll jump.

This will override the browser’s default auto-scroll behavior and make sure every time you open a panel, you start at the top of its content.

内容的提问来源于stack exchange,提问作者Michelle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:41:55