2015-12-15 50 views
1

在下面的代碼,渲染鼠標位置使用document.write對象

 <script> 
      var mie = (navigator.appName == "Microsoft Internet Explorer") ? true : false; 
      if(!mie){ 
       document.captureEvents(Event.MOUSEMOVE); 
      } 
      document.onmousemove = mousePos; 

      var mouseX = 0; 
      var mouseY = 0; 

      function mousePos(e){ 
       if(!mie){ 
        mouseX = e.pageX; 
        mouseY = e.pageY; 
       } 
       else{ 
        mouseX = e.clientX + document.body.scrollLeft; 
        mouseY = e.clientY + document.body.scrollRight; 
       } 

       /*document.formex.mousex.value = mouseX; 
       document.formex.mousey.value = mouseY;*/ 
       document.write("X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date());  
       return true; 
      } 
    </script> 

期望輸出是呈現用於在移動每鼠標位置的每個新條目。

我只能使用document.write對象呈現一個鼠標位置。有更好的方法來渲染嗎?

+0

使用'console.log' :) – HTDE

+0

http://codepen.io/anon/pen/GoopvW?editors = 001 – HTDE

回答

0

document.writeclears the document,所有的事件處理程序裏面

試試這個,而不是

<script> 
      var mie = (navigator.appName == "Microsoft Internet Explorer") ? true : false; 
      if(!mie){ 
       document.captureEvents(Event.MOUSEMOVE); 
      } 
      document.onmousemove = mousePos; 

      var mouseX = 0; 
      var mouseY = 0; 

      function mousePos(e){ 
       if(!mie){ 
        mouseX = e.pageX; 
        mouseY = e.pageY; 
       } 
       else{ 
        mouseX = e.clientX + document.body.scrollLeft; 
        mouseY = e.clientY + document.body.scrollRight; 
       } 

       /*document.formex.mousex.value = mouseX; 
       document.formex.mousey.value = mouseY;*/ 
       document.write("X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date());  
document.onmousemove = mousePos; 
       return true; 
      } 
    </script> 

觀察return true之前添加到事件再次綁定新的聲明。

或只是如果要追加然後做

document.body.innerHTML += "X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date() + " </br>"; 
+0

雖然這重新綁定的JavaScript,它仍然抹去了整個頁面。我們應該考慮諸如'document.body.innerHTML =「X:」+ mouseX +「; Y:」+ mouseY +「; Time:」+ new Date());' – teynon

+0

@Tom是的,這也是真的 – gurvinder372

+0

JavaScript可能很有趣。我記得在使用iframe的時候,我可以用一個函數創建一個iframe,並在外部作用域中引用它,然後刪除iframe並調用函數。好玩。沒有環境,只是運行時。 – HTDE

0

不要使用文件撰寫改用innerHTML的使用該行,而不是document.write(禮貌@湯姆)

document.body.innerHTML = "X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date(); 

。請參閱演示鏈接。

 var mie = (navigator.appName == "Microsoft Internet Explorer") ? true : false; 
     if(!mie){ 
      document.captureEvents(Event.MOUSEMOVE); 
     } 
     document.onmousemove = mousePos; 

     var mouseX = 0; 
     var mouseY = 0; 

     function mousePos(e){ 
      if(!mie){ 
       mouseX = e.pageX; 
       mouseY = e.pageY; 
      } 
      else{ 
       mouseX = e.clientX + document.body.scrollLeft; 
       mouseY = e.clientY + document.body.scrollRight; 
      } 


      document.body.innerHTML = "X: " + mouseX + ";Y: " + mouseY + "; Time: " + new Date();  
      return true; 
     } 

Demo

感謝,

阿肖克