SharePoint 2010自定义XSLT如何隐藏未显示项的高度?
嘿,这个问题我之前帮客户处理过!核心原因是即使没有匹配的列表项,你的XSLT还是渲染了外层的table(或者分组相关的空元素),这些空元素的默认样式(比如padding、border、min-height)会导致容器出现额外高度。下面给你两个最直接的解决方案:
方案1:仅在有匹配项时渲染整个表格
最简单的办法是用<xsl:if>判断$Rows是否有数据,只有当存在匹配项时才输出整个表格结构。这样没有数据时,承载div里什么都不会输出,自然不会有多余高度。
修改后的核心代码如下:
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"> <xsl:output method="html" indent="no"/> <xsl:param name="ListUrlDir"/> <xsl:param name="PageUrl"/> <!-- 优化:用ddwrt:GetVar更可靠地获取查询参数 --> <xsl:variable name="CurrentID" select="ddwrt:GetVar('ID', $PageUrl)"/> <xsl:variable name="Rows" select="/dsQueryResponse/Rows/Row[@ID = $CurrentID]"/> <xsl:template match="/"> <!-- 关键:先检查是否有匹配的行 --> <xsl:if test="$Rows"> <table cellspacing="0" cellpadding="0"> <xsl:for-each select="$Rows"> <xsl:sort select="@Group"/> <xsl:variable name="newGroup" select="ddwrt:NameChanged(string(@Group),1)"/> <tr id="group0"> <th class="my-rteElement-PubColoredHeading2" colspan="99"><xsl:value-of select="@Group"/></th> </tr> <tr id="group1"> <td class="ms-gb" colspan="99" style="border:none"> <a onclick="javascript:ExpGroupBy(this);return false;" href="{$ListUrlDir}/dispform.aspx?id={@ID}"> <img border="0" alt="展开/收起" src="/_layouts/images/minus.gif"/> <!-- 补充你原来的图片和文本内容 --> </a> </td> </tr> <!-- 你的数据行内容 --> </xsl:for-each> </table> </xsl:if> </xsl:template> </xsl:stylesheet>
方案2:配合CSS处理极端情况
如果你的承载div本身有默认的padding或margin(比如SharePoint WebPart的容器),可以额外加个CSS规则,确保没有内容时容器高度为0:
/* 假设承载div的类是list-container,根据实际情况调整 */ .list-container:empty { height: 0; overflow: hidden; padding: 0; margin: 0; }
另外提醒一下:原来用substring-after($PageUrl,'=')获取ID的写法有隐患,如果URL里有多个=符号(比如?ID=5&other=xxx)会出错,改用ddwrt:GetVar("ID", $PageUrl)能更可靠地提取查询字符串参数。
内容的提问来源于stack exchange,提问作者YogaPanda
相关产品推荐
相关产品推荐

