Javascript 调用不活动的 Bootstrap 选项卡内容

Javascript call on inactive Bootstrap tab content

我有一个包含 Bootstrap (v3) 选项卡的页面:

https://getbootstrap.com/docs/3.3/javascript/#tabs

我在每个选项卡中呈现了一些迷你图:

https://omnipotent.net/jquery.sparkline/#s-docs

并这样调用:

  $('.sparkline-pie-remaining').sparkline('html', {
    type: 'pie',
    sliceColors: ['#1ab394', '#ed5565','#ddd'],
    width: '18',
    height: '18',
    offset: -90,
    disableTooltips: true,
    borderWidth: 1,
    borderColor: '#676a6c'
  });

问题是在非活动选项卡上不会调用它。当显示选项卡时我尝试了一个回调,但每次选项卡更改和图表被清除时它都会调用它。

如何在呈现页面时在非活动选项卡内容上进行此调用?这是重现问题的 CodePen:

https://codepen.io/dantappin/pen/rNegXOP

迷你图未在非活动选项卡中呈现的原因是因为该选项卡面板 div 具有“显示:none”属性。这是 documentation you provided 的一部分(参见“隐藏的迷你图”部分):

If you try to display a sparkline in a tag that's currently not visible (ie. the tag or one of its parents are set to display:none) then you'll find that the sparkline hasn't been rendered when you finally do make the tag visible. This is because a tag with display:none has no size, and thus a canvas can't be created and sized for the sparkline to be rendered to.

The solution is to call the $.sparkline_display_visible() function anytime a sparkline may have become visible so that it can be correctly rendered. This is the technique this site uses to handle the sparklines that are hidden in the different tabbed sections; the site calls the routine in the tab-changed callback.

解决方案也包含在相同的引用文本中。您可以通过在选项卡按钮或选项卡面板 div 上附加事件处理程序并在选项卡首次激活时调用 $.sparkline_display_visible() 来实现此目的。

编辑:您可以通过激活选项卡并在 JS 控制台中执行一次 $.sparkline_display_visible() 来快速测试。