鼠标跟随效果

实现效果:鼠标经过显示tip层,并且tip层随鼠标移动,鼠标移出隐藏tip层。
先获取事件对象,然后通过把事件对象的clientX和clientY赋值给div的left和top。需要注意的是,这个跟随div是要绝对定位的,并且不要嵌套在内容层中。

js代码:

function follow(cont, tip){
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
function getEvent(event){
return window.event || event;
}
function showFollow(event,el){
event = getEvent(event);
el.style.display = 'block';
el.style.left = event.clientX+5+'px';
el.style.top = event.clientY+5+'px';
}
function hideFollow(el){
el.style.display = 'none';
}
var contArr = getElementsByClass(cont),
tipArr = getElementsByClass(tip),
len = contArr.length;
for (var i = 0; i < len; i++){(function(i){
contArr[i].onmousemove = function(event){showFollow(event, tipArr[i])};
contArr[i].onmouseout = function(){hideFollow(tipArr[i])};
})(i)
}
}
follow('cont', 'tip');

参数说明:
cont:鼠标经过内容或按钮层的类名;
tip:鼠标经过显示的层(随鼠标移动)。

html代码:

<div class="cont">这是内容div1</div>
<div class="tip">这是跟随1</div>
<div class="cont">这是内容div2 </div>
<div class="tip">这是跟随2</div>

css代码:

.cont{float:left; width:200px; height:200px; margin:10px; background-color:#099; color:#F00;}
.tip
{ position:absolute; display:none; width:100px; height:100px; background-color:#630; color:#fff;}
原文地址:https://www.cnblogs.com/bianyuan/p/2356387.html