div跟随鼠标事件(onmousemove)

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

CSS:

<style>

#div1{

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跟随鼠标移动,非常简单。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注