js实现跟随鼠标移动的提示框

本文介绍如何利用JavaScript、CSS和HTML创建一个跟随鼠标移动的提示框。通过监听鼠标移动事件,动态更新提示框的位置,并展示相应的内容,为用户提供实时反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width: 300px;height: 40px;background: #ccc;margin: 20px auto;position: relative;}
        .box *{margin: 0;}
        .box h2{line-height: 40px;}
        .box p{width: 200px;background: #eee;font-size: 14px;position: absolute;left:0;top:0;display: none;z-index: 1;}

        #box{width: 100px;height: 100px;background: red;display: block}
        #box:hover{display: none;}

    </style>
</head>
<body>
    <div class="box">
        <h2>这是一个标题1</h2>
        <p>这是标题1对应的详细文本这是标题1对应的详细文本这是标题1
        对应的详细文本这是标题1对应的详细文本这是标题1
        对应的详细文本这是标题1对应的详细文本这是标题1</p>
    </div>
    <div class="box">
        <h2>这是一个标题2</h2>
        <p>这是标题2对应的详细文本题2对应的详细文本题2对应的详细文本题2
        对应的详细文本题2对应的详细文本题2对应的详细文本题2
        对应的详细文本题2对应的详细文本题2</p>
    </div>

    <div id="box"></div>
</body>
<script>
    var ah2 = document.querySelectorAll(".box h2");

    for(var i=0;i<ah2.length;i++){
        ah2[i].onmouseover = function(){
            // console.log(this); 
            this.nextElementSibling.style.display = "block";
        }
        ah2[i].onmousemove = function(eve){
            // console.log(this);
            var e = eve || window.event;
            // 将h2后面的p的定位位置,设置成鼠标的坐标,稍微往后一点,防止阻挡鼠标放在事件源身上
            this.nextElementSibling.style.left = e.offsetX + 5 + "px";
            this.nextElementSibling.style.top = e.offsetY + 5 + "px";
        }
        ah2[i].onmouseout = function(){
            // console.log(this);
            this.nextElementSibling.style.display = "none";
        }
    }

</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值