js effect div follow the mouse

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_41194704/article/details/102778471

js effect div follow the mouse

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
.div{
    width: 200px;
    height: 200px;
    background: red;
    position: absolute;
    cursor: pointer;
}
</style>
<body>
    <div class="da">
    <div class="div"></div>
</div>
</body>
<script>
//1.找到跟随鼠标移动的div
var div=document.querySelector('.div');
//2.div的鼠标移动事件,但因为鼠标事件的要求是,鼠标在要操作的元素上。所以,我们用window来做
window.onmousemove=function(evt){
    //3.得到鼠标的当前坐标
    //evt.client 鼠标在可视区中的坐标
    //evt.clientX  鼠标的X轴坐标
    //evt.cliebtY  鼠标的Y轴坐标
    var x=evt.clientX;
    var y=evt.clientY;
    //5.扩展:设置鼠标在元素的中间
    //如果想要设置鼠标在元素的中间,那么就是div的宽度的一半与高度的一半的交点,就是中心点
    //元素的宽度的属性是div.offsetWidth
    //元素的高度的属性是div.offsetHeight
    //那么我们要考虑的是加还是减。
    //如果是加的话,那么就是鼠标显示在0,0坐标,但实际的坐标却是100,100;就会向下,右
    //减的话,鼠标显示在0,0坐标,实际的坐标在-100,-100,向上,左
    //所以是减
    x=x-div.offsetWidth/2;
    y=y-div.offsetHeight/2;
    //4.设置div的left,top,因为div是设置了绝对定位,像这种移动的都需要设置定位
    //div的左上角点,就是鼠标的坐标
    div.style.left=x+'px';
    div.style.top=y+'px';
}
</script>
</html>

Guess you like

Origin blog.csdn.net/qq_41194704/article/details/102778471