又是新的一天网上冲浪,在bing的搜索页面下看到这样一个效果:

即弹出框随着鼠标的移动而移动。思路大概为:

  • 调用onmousemove函数,将鼠标的当前位置赋予弹出框即可

    //html
    <div id="alert">
        <div class="img">
            <img src="./img/trees-576751_640.png" alt="">
        </div>
        Look At Me
    </div>
    
    <div id="clickMe">Touch Me</div>
    /*css*/
    #clickMe {
        width: 100px;
        height: 40px;
        margin: 100px auto;
        cursor: pointer;
        background-color: brown;
        color: white;
        text-align: center;
        line-height: 40px;
        border-radius: 50%;
    }
    
    #alert {
        width: 200px;
        height: 200px;
        text-align: center;
        background-color: tomato;
        font-size: 20px;
        position: absolute;
        display: none;
    }
    .img{
        width: 80%;
        height: 35%;
        margin: 20% auto;
        border: 2px dotted #ffffff;
    }
    .img img{
        width: 100%;
        height: 100%;
    }
    //javascript
    var click = document.getElementById("clickMe")
    var alert = document.getElementById("alert")
    
    click.onmousemove = function (e) {
        alert.style.left = e.clientX + 20 + "px"
        alert.style.top = e.clientY + 10 + "px"
        alert.style.display = "block";
    }
    
    click.onmouseout = function (e) {
        alert.style.display = "none";
    }

    效果如下:

12-14 00:19