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

如何实现鼠标悬停图片时title属性显示用户名?

实现鼠标悬停图片时显示指定标签的用户名

方法一:原生JavaScript实现

先补全你的HTML结构(原代码缺少闭合标签):

<div class="profile">
    <img class="image" src="images/7.png" title="here - that it will show the tag value">
    <div class="names-row">
        <p class="name">User</p>
        <p class="tag">@username</p>
    </div>
</div>

添加JavaScript代码,将其放在页面底部或DOMContentLoaded事件中执行:

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 获取所有profile容器
    const profiles = document.querySelectorAll('.profile');
    
    profiles.forEach(profile => {
        const img = profile.querySelector('.image');
        const tagText = profile.querySelector('.tag').textContent.trim();
        
        // 直接设置img的title属性为tag的内容
        img.title = tagText;

        // 若tag内容会动态变化,可改用mouseover事件实时更新
        // img.addEventListener('mouseover', function() {
        //     this.title = profile.querySelector('.tag').textContent.trim();
        // });
    });
});

方法二:jQuery实现(项目已引入jQuery时使用)

补全HTML结构后,添加以下jQuery代码:

$(document).ready(function() {
    $('.profile').each(function() {
        const tagText = $(this).find('.tag').text().trim();
        $(this).find('.image').attr('title', tagText);
    });
});

说明

两种方法都会将每个.profile容器下的图片title属性替换为对应.tag标签的文本内容,鼠标悬停图片时即可显示用户名。如果.tag内容是动态生成的,确保代码在内容加载完成后再执行。

内容的提问来源于stack exchange,提问作者rolandx2022

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:05:33