div跟随鼠标事件(onmousemove)

div跟随鼠标移动是依赖于鼠标移动事件(onmousemove),废话不多说直接上代码:

CSS:

<style>

#div1{

width:50px;

height:50px;

border-radius:25px;

background-color:rgba(0,0,0,0.5);

cursor:pointer;

position:absolute;

top:50%;

left:50%;

transform:translate(-50%,-50%)

}

</style>

HTML:

<div id="div1"></div>

JS:

<script>

document.onmousemove = function(ev){

var oEvent=ev||event;

var oDiv=document.getElementById('div1');

oDiv.style.left=oEvent.clientX+'px';

oDiv.style.top=oEvent.clientY+'px';

}

</script>

以上三部分搞定div跟随鼠标移动,非常简单。

 

posted @ 2018-12-18 10:11  james_liang  阅读(2254)  评论(0编辑  收藏  举报