点击新闻弹出新闻内容,并且新闻内容根据鼠标移动

点击新闻弹出新闻内容,并且新闻内容根据鼠标移动

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width: 800px;padding:10px;border: solid 1px black;margin: 40px auto;
        position: relative;}

        .title h2{padding: 5px 0;background: #a9a;}

        .msg p{width: 400px;font-size: 14px;color: #222;border: solid 1px black;background: #efefef;
        margin: 0;
        display: none;
        position: absolute;left:0;top:0;}
    </style>
</head>
<body>
    <div class="box">
        <div class="title">
            <h2>全球确诊超409万例!俄罗斯总统新闻秘书确诊,美国副总统有新动作</h2>
            <h2>“无国界医生”派遣团队前往疫情严重的美国原住民社区</h2>
        </div>
        <div class="msg">
            <p>超过100个新冠肺炎疫苗项目正在进行当地时间12日,世卫组织发言人玛格丽特·哈里斯表示,目前已有超过100个新冠肺炎疫苗项目正在进行。但针对冠状病毒的疫苗研发有难度,正在加速进行。疫情最新情况美国确诊病例超过136万例据约翰斯·霍普金斯大学数据,截至美东时间12日17时32分,美国新冠肺炎确诊病例为1366350例,死亡82105例。</p>
            <p>据外媒BGR报道,“无国界医生”(Doctors Without Borders)是一个国际医疗人道主义组织,以在冲突地区和卫生保健系统崩溃的地方开展活动,为受苦受难的民众提供所需的护理而闻名。由于美国一个地区的新冠疫情已经变得非常严重,该组织最近派出了一支队伍,首次在当地开展行动。</p>
        </div>
    </div>

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

    for(var i=0;i<ah2.length;i++){
        // 给每个h2绑定索引,方便将来在事件中获取
        ah2[i].index = i;
        // 鼠标进入
        ah2[i].onmouseover = function(){
            // 隐藏所有
            for(var j=0;j<ap.length;j++){
                ap[j].style.display = "none";
            }
            // 根据当前事件元素的索引,显示对应的p
            ap[this.index].style.display = "block";
        }
        // 鼠标离开
        ah2[i].onmouseout = function(){
            // 隐藏所有
            for(var j=0;j<ap.length;j++){
                ap[j].style.display = "none";
            }
        }

        ah2[i].onmousemove = function(eve){
            var e = eve || window.event;
            //+10是解决闪的问题
            ap[this.index].style.left = e.offsetX + this.offsetLeft + 10 + "px";
            console.log(e.offsetX)
            console.log(this.offsetLeft)
            ap[this.index].style.top = e.offsetY + this.offsetTop + 10 + "px"
        }
    }
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/cupid10/p/12897760.html