亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

簡單實現(xiàn)js鼠標(biāo)跟隨效果

 更新時間:2020年08月02日 10:56:17   作者:diasa  
這篇文章主要教大家如何簡單實現(xiàn)js鼠標(biāo)跟隨效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了js鼠標(biāo)跟隨效果展示的具體代碼,供大家參考,具體內(nèi)容如下

<!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;
   }
  }
  //以下代碼會出現(xiàn)一個問題,當(dāng)鼠標(biāo)移動過快的時候,鼠標(biāo)會進入到mark這個盒子,會觸發(fā)它的mouseover行為,由于事件的冒泡傳播機制,導(dǎo)致box的mouseover會重新被觸發(fā),導(dǎo)致紅色盒子一直在不斷的創(chuàng)建
  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";
   }

  }
  //依然有問題:鼠標(biāo)快速移動,首先會到mark上,此時瀏覽器在計算mark的位置,計算完成,mark到達指定的位置,此時鼠標(biāo)又重新回到box上,觸發(fā)了box的mouseover,也觸發(fā)了mark的mouseout,也會傳播到box的mouseout上,會把mark先刪除,然后在創(chuàng)建
  box.onmouseout = function(e){
   e = e || window.event;
   var mark = document.getElementById('mark');
   if(mark){
    this.removeChild(mark);
   }

  }

  //上面代碼也可以通過將over和out事件分別改為enter和leave 
  //onmouseenter和onmouseover都是鼠標(biāo)滑上去的行為,但是onmouseenter瀏覽器默認(rèn)阻止了它的冒泡傳播(mark的onmouseenter行為觸發(fā),不會傳播到box);而onmouseover是存在冒泡傳播的,想要阻止的話需要手動阻止
 </script>
</body>
</html>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論