首页 > 解决方案 > 渲染后如何获取在检查元素窗口中看到的 DOM 内容?

问题描述

我正在尝试使用 JS 使用 MathJax 生成 SVG 并像这里一样对其进行动画处理

在我的代码中,我有

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    SVG: {
      useGlobalCache: true,
      useFontCache: false
    }
  })
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-AMS_SVG"></script>
<div id="sup">$$a$$</div>

当我使用检查元素检查渲染的 DOM 时,我得到dividsup为的内容

<span class="MathJax_Preview" style="color: inherit; display: none;"></span>
<div class="MathJax_SVG_Display" style="text-align: center;">
    <span style="font-size: 100%; display: inline-block; position: relative;" class="MathJax_SVG" id="MathJax-Element-1-Frame" tabindex="0" data-mathml="<math xmlns=&quot;http://www.w3.org/1998/Math/MathML&quot; display=&quot;block&quot;><mi>a</mi></math>" role="presentation">
        <svg xmlns:xlink="http://www.w3.org/1999/xlink" width="1.23ex" height="1.454ex" style="vertical-align: -0.227ex;" viewBox="0 -528.2 529.5 625.9" role="img" focusable="false" aria-hidden="true">
            <g stroke="currentColor" fill="currentColor" stroke-width="0" transform="matrix(1 0 0 -1 0 0)">
                <path stroke-width="1" d="M33 157Q33 258 109 349T280 441Q331 441 370 392Q386 422 416 422Q429 422 439 414T449 394Q449 381 412 234T374 68Q374 43 381 35T402 26Q411 27 422 35Q443 55 463 131Q469 151 473 152Q475 153 483 153H487Q506 153 506 144Q506 138 501 117T481 63T449 13Q436 0 417 -8Q409 -10 393 -10Q359 -10 336 5T306 36L300 51Q299 52 296 50Q294 48 292 46Q233 -10 172 -10Q117 -10 75 30T33 157ZM351 328Q351 334 346 350T323 385T277 405Q242 405 210 374T160 293Q131 214 119 129Q119 126 119 118T118 106Q118 61 136 44T179 26Q217 26 254 59T298 110Q300 114 325 217T351 328Z"></path>
            </g>
        </svg>
        <span class="MJX_Assistive_MathML MJX_Assistive_MathML_Block" role="presentation">
            <math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><mi>a</mi></math>
        </span>
    </span>
</div>
<script type="math/tex; mode=display" id="MathJax-Element-1">a</script>

但是当我尝试使用 id 获取innerHTMLdivsup

window.addEventListener('load', function(){
  console.log(document.getElementById("sup").innerHTML);
})

我得到$$a$$作为输出。

如何获得与检查元素中显示的输出相同的输出?

标签: javascripthtmlsvg

解决方案


你的问题是当你打开MathJax时永远不会加载。console.logwindow.load

首先,您需要等到MathJax加载和渲染才能获得所需的输出结果。

我发现这个问题可能对你有帮助

与 MathJax 的启动操作同步的方法是注册一个 StartupHook,它将在启动完成时触发。例如,您可以使用 MathJax.Hub.Register.StartupHook("End",function () { console.log(document.getElementById("sup").innerHTML); });


推荐阅读