本文實例為大家分享了js鼠標跟隨效果展示的具體代碼,供大家參考,具體內容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body,div{
margin:0;
padding:0;
}
#box{
position:relative;
margin:20px auto;
width:300px;
height:300px;
background:#008000;
}
#mark{
position:absolute;
top:0;
left:0;
width:100px;
height:100px;
background:red;
}
</style>
</head>
<body>
<div id='box'>
</div>
<script>
var box = document.getElementById('box');
box.onmouseover = function(e){
e = e || window.event;
var mark = document.createElement('div');
mark.id = "mark";
this.appendChild(mark);
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
//阻止mark盒子的onmouseover事件的冒泡傳播
mark.onmouseover = function(e){
e = e || window.event;
e.stopPropagation ? e.stopPropagation():e.cancelBubble = true;
}
mark.onmouseout = function(e){
e = e || window.event;
e.stopPropagation ? e.stopPropagation():e.cancelBubble = true;
}
}
//以下代碼會出現一個問題,當鼠標移動過快的時候,鼠標會進入到mark這個盒子,會觸發它的mouseover行為,由于事件的冒泡傳播機制,導致box的mouseover會重新被觸發,導致紅色盒子一直在不斷的創建
box.onmousemove = function(e){
e = e || window.event;
var mark = document.getElementById('mark');
if(mark){
mark.style.left = e.clientX - this.offsetLeft + 5 + "px";
mark.style.top = e.clientY - this.offsetTop + 5 + "px";
}
}
//依然有問題:鼠標快速移動,首先會到mark上,此時瀏覽器在計算mark的位置,計算完成,mark到達指定的位置,此時鼠標又重新回到box上,觸發了box的mouseover,也觸發了mark的mouseout,也會傳播到box的mouseout上,會把mark先刪除,然后在創建
box.onmouseout = function(e){
e = e || window.event;
var mark = document.getElementById('mark');
if(mark){
this.removeChild(mark);
}
}
//上面代碼也可以通過將over和out事件分別改為enter和leave
//onmouseenter和onmouseover都是鼠標滑上去的行為,但是onmouseenter瀏覽器默認阻止了它的冒泡傳播(mark的onmouseenter行為觸發,不會傳播到box);而onmouseover是存在冒泡傳播的,想要阻止的話需要手動阻止
</script>
</body>
</html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。