怎么实现html元素跟随鼠标移动而移动?

html-css03

怎么实现html元素跟随鼠标移动而移动?,第1张

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<style>

#div1 {width:100px height:100px background:red position:absolute}

</style>

<meta http-equiv="Content-Type" content="text/html charset=utf-8" />

<title>无标题文档</title>

<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>

</head>

<body>

<div id="div1">

</div>

</body>

</html>

这个提示是标签默认的title属性吧?如果是的话,无需任何JS,直接为导航的标签添加title属性即可。例如:

<a href="xxxx" title="主站">主站</a>

<a href="xxxx" title="画友">画友</a>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312" />

<title>无标题文档 </title>

<script language="javascript">

var Atop = 0

function inix(){

Atop = findPos(document.getElementByIdx("Layer1"))[1]

}

function move(){

document.getElementByIdx("Layer1").style.pixelTop = Atop + document.documentElement.scrollTop

}

function findPos(obj){

var curleft = curtop = 0

if (obj.offsetParent) {

do {

curleft += obj.offsetLeft

curtop += obj.offsetTop

}

while (obj = obj.offsetParent)

}

return [curleft, curtop]

}

window.onscroll = move

</script>

<style type="text/css">

<!-- #Layer1 {

position: absolute

left: 48px

top: 49px

width: 82px

height: 82px

z-index: 1

}

-->

</style>

</head>

<body onload="inix()">

<div id="Layer1">

<img src="images/float_advclose1.gif" width="80" height="80" />

</div>

<table width="200" border="1" align="center">

<tr>

<td>

<img src="images/xiaojie1.jpg" width="768" height="1113" />

</td>

</tr>

</table>

</body>

</html>

解释:

1 代码:window.onscroll = move

页面滚动window的onscroll调用move方法。

2 函数 function findPos(obj)

获得一个元素在页面上的绝对位置。要先获得这个元素与父元素的相对位置再获得父元素的父元素的相对位置, 一直循环到根元素,然后把相对位置相加。