Visualforce嵌套pageBlockSections默认折叠后多余空格如何修复
问题根因
你把<script>标签直接嵌入到<apex:pageBlockSection>内部,Salesforce渲染页面时,会把不属于<apex:pageBlockSectionItem>的非标准组件自动识别为内容项,额外生成一对表格单元格(td)占住section的第一列位置,后续的正式内容就被挤到第二列,自然就出现了前置空白、内容看似居中的异常。
最优修复方案
直接用<apex:pageBlockSection>原生的collapsed属性即可实现默认折叠,完全不需要额外写JS脚本,从根源上避免布局异常:
<apex:page > <apex:pageBlock> <apex:pageBlockSection title="Option 1" id="op1" collapsed="true"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection title="Option 2" id="op2" collapsed="true"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection title="Option 3" id="op3" collapsed="true"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:page>
替代方案(特殊场景需用JS实现时)
如果有业务逻辑必须通过JS控制折叠状态,就把所有折叠逻辑的JS代码统一放到页面底部,不要嵌入到section内部破坏布局结构:
<apex:page > <apex:pageBlock> <apex:pageBlockSection title="Option 1" id="op1"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection title="Option 2" id="op2"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection title="Option 3" id="op3"> <apex:pageBlockSectionItem> <span>This is a test</span> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> <!-- 脚本统一放到页面底部,不侵入section内部结构 --> <script> twistSection(document.getElementById('img_{!$Component.op1}')); twistSection(document.getElementById('img_{!$Component.op2}')); twistSection(document.getElementById('img_{!$Component.op3}')); </script> </apex:page>
内容的提问来源于stack exchange,提问作者Hasan Zubairi
相关产品推荐
相关产品推荐

