欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

本文實(shí)例為大家分享了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;
   }
  }
  //以下代碼會(huì)出現(xiàn)一個(gè)問(wèn)題,當(dāng)鼠標(biāo)移動(dòng)過(guò)快的時(shí)候,鼠標(biāo)會(huì)進(jìn)入到mark這個(gè)盒子,會(huì)觸發(fā)它的mouseover行為,由于事件的冒泡傳播機(jī)制,導(dǎo)致box的mouseover會(huì)重新被觸發(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";
   }

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

  }

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

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

相關(guān)文章

最新評(píng)論