点击触发后Div不遵守设置宽高的问题排查
问题原因及修复方案
核心错误点
- 宽高未加单位:你给
aladin-lite-div设置的width:355;height:250没有指定单位px,浏览器无法识别有效尺寸,导致容器被挤压变形。 - 容器初始状态未隐藏:这个div默认处于显示状态,即使无内容也会占据布局空间,且你在点击后才设置
display:block,逻辑倒置,应该一开始就隐藏。 - Flex子项未固定宽度:包裹图片和Aladin容器的父div没有设置固定宽度,在flex布局中会被右侧表格挤压,导致宽度缩窄。
修复后的关键代码调整
- 修正Aladin容器样式,添加单位并设置初始隐藏:
<div id="aladin-lite-div" style="width:355px;height:250px;display:none"></div>
- 给图片所在的父div添加固定宽度,避免flex布局挤压:
<div style="text-align: center; width:355px;">
完整修复后的代码片段
<div style="display: flex; justify-content: space-between;"> <div style="text-align: center; width:355px;"> <!-- Your image --> <img id="myImage" src="https://raw.githubusercontent.com/ucc23/test/main/berkeley29.webp" alt="Clickable Image" style="width:355px;height:250px; cursor: pointer;"> <!-- Div to contain Aladin Lite viewer --> <div id="aladin-lite-div" style="width:355px;height:250px;display:none"></div> <!-- Aladin Lite script (will be loaded after the image is clicked) --> <script type="text/javascript"> // Function to load Aladin Lite after image click and hide the image function loadAladinLiteAndHideImage() { // Dynamically load the Aladin Lite script let aladinScript = document.createElement('script'); aladinScript.src = "https://aladin.cds.unistra.fr/AladinLite/api/v3/latest/aladin.js"; aladinScript.charset = "utf-8"; aladinScript.onload = function () { A.init.then(() => { let aladin = A.aladin('#aladin-lite-div', {survey:"P/DSS2/color", fov:0.1, target: "103.269 16.929"}); // Remove the image document.getElementById('myImage').remove(); // Show the Aladin Lite viewer document.getElementById('aladin-lite-div').style.display = 'block'; }); }; document.head.appendChild(aladinScript); } // Event listener for image click document.getElementById('myImage').addEventListener('click', loadAladinLiteAndHideImage); </script> </div> <!-- Left block --> <table style="text-align: center; width:355px;height:250px;"> <!-- Row 1 (title) --> <tr> <td colspan="5"><h3>Table title</h3></td> </tr> <!-- Row 2 --> <tr> <th><a>C1</a></th> <th><a>C2</a></th> <th><a>C3</a></th> <th><a>C4</a></th> <th><a>C5</a></th> </tr> <!-- Row 3 --> <tr> <td>1.0</td> <td>0.52</td> <td>9.7</td> <td>534</td> <td>3.0</td> </tr> </table> </div>
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

