本文實(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;      }    }    //以下代碼會出現(xiàn)一個(gè)問題,當(dāng)鼠標(biāo)移動(dòng)過快的時(shí)候,鼠標(biāo)會進(jìn)入到mark這個(gè)盒子,會觸發(fā)它的mouseover行為,由于事件的冒泡傳播機(jī)制,導(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)快速移動(dòng),首先會到mark上,此時(shí)瀏覽器在計(jì)算mark的位置,計(jì)算完成,mark到達(dá)指定的位置,此時(shí)鼠標(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是存在冒泡傳播的,想要阻止的話需要手動(dòng)阻止  </script></body></html>以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答