js实现弹出框跟随鼠标移动

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

js实现弹出框跟随鼠标移动_第1张图片

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

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

    //html
    
    Look At Me
    Touch Me
    /*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";
    }

    效果如下:
    js实现弹出框跟随鼠标移动_第2张图片

你可能感兴趣的:(js实现弹出框跟随鼠标移动)