使用innerHTML构建DOM时空白字符异常问题的排查与解决
Leaflet弹窗DOM渲染空白异常解决办法
原实现代码(JS)
var popupVhc1 = L.DomUtil.create('div', 'popup-vhcmap'); tablepopupVhc1 = L.DomUtil.create('table','table table-infopopup',popupVhc1); trpopupVhc1 = L.DomUtil.create('tr','',tablepopupVhc1); tdiconpopupVhc1 = L.DomUtil.create('td','col-1 align-midle bg-popup-gre',trpopupVhc1); infoiconpopupVhc1 = L.DomUtil.create('i','bi bi-car-front-fill text-icon-popup',tdiconpopupVhc1); tdcontentpopupVhc1 = L.DomUtil.create('td','col-6 td-content-popup',trpopupVhc1); tdcontentpopupVhc1.innerHTML += '<b>B 8384 UCR</b><br>'; tdcontentpopupVhc1.innerHTML += 'Moving - 84 Kph - 25<sup>o</sup><br>'; tdcontentpopupVhc1.innerHTML += '24-09-2024 20:38:32';
对应CSS样式
div.popup-vhcmap { font-size: 0.75rem; width: 200px; height: 80px; box-shadow: 0 0 1px 1px #6d6d6d; border-radius: 3px; text-align: center; } table.table-infopopup { height: 100%; width: 99%; } td.bg-popup-gre { background-color: #03b420; text-align: center; } td.td-content-popup { background-color: #fff; text-align: left; padding-left: 5px; line-height: 1.5; } i.text-icon-popup { font-weight: bold; color: #fff; }
问题现象
渲染后出现空白字符异常,移除<b>或<sup>标签空白会消失,但无法保留预期格式。预期渲染效果:
B 8384 UCR
Moving- 84 Kph - 25o
24-09-2024 20:38:32
解决方法
将每段内容用<span>标签包裹,修改后的JS代码如下:
tdcontentpopupVhc1.innerHTML += '<span><b>B 8384 UCR</b></span><br>'; tdcontentpopupVhc1.innerHTML += '<span>Moving - 84 Kph - 25<sup>o</sup></span><br>'; tdcontentpopupVhc1.innerHTML += '<span>24-09-2024 20:38:32</span>'
修改后渲染结果符合预期。
内容的提问来源于stack exchange,提问作者dvaa
相关产品推荐
相关产品推荐

