You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf中带图片按钮无法显示,求正确实现方法

Thymeleaf创建带图片按钮的正确方法

问题描述

我正在将网站从JSF迁移到Spring MVC(项目地址:https://github.com/iva-nova-e-katerina/mysite_v2),想要创建带图片的按钮,使用了如下Thymeleaf代码:

<th:button type="button" th:image="@{/dist/images/ru32x32.png}" onclick="window.location.replace('?lang=ru');"/>

但按钮上的图片无法显示,不过图片地址http://localhost:8080/dist/images/ru32x32.png可正常访问,请告知Thymeleaf中创建带图片按钮的正确方法?

解决方案

Thymeleaf的th:image属性仅适用于<img>标签,不能直接作用在<button>上,这是导致图片无法显示的核心原因。以下两种方法可实现带图片的按钮:

  • 方法1:按钮内嵌套<img>标签
    这是最直观的实现方式,在按钮内部放置<img>元素,通过th:src绑定图片路径:

    <button type="button" onclick="window.location.replace('?lang=ru');">
        <img th:src="@{/dist/images/ru32x32.png}" alt="切换为俄语"/>
    </button>
    

    该方式能保证图片正常渲染,还可通过alt属性添加无障碍描述,提升页面可用性。

  • 方法2:使用CSS背景图
    若需要将图片作为按钮的背景样式,可通过th:style动态设置背景图片路径,同时补充必要CSS属性优化显示效果:

    <button type="button" 
            th:style="'background-image: url(' + @{/dist/images/ru32x32.png} + ');'"
            onclick="window.location.replace('?lang=ru');"
            style="background-size: contain; background-repeat: no-repeat; width: 32px; height: 32px; border: none; cursor: pointer;">
    </button>
    

    其中background-size、width、height等样式可根据图片尺寸和需求灵活调整。

内容的提问来源于stack exchange,提问作者Ekaterina Ivanova iceja.net

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:32:49