[英]how to make element appear at the spot where mouse clicks in javascript
我想從空白頁開始,然后當用戶(鼠標)單擊頁面中的任何位置時,該位置就會出現一個框。
到目前為止,這是我所要做的,我先隱藏了框,然后通過添加事件偵聽器來更改了樣式,但是如何創建另一個事件,該事件允許用戶單擊任意位置,出現框,然后在另一個位置再次單擊框出現在該位置。 -僅使用原始Javascript
在此先感謝您,這是我的html / css代碼:
<div id ="box"></div>
#box{
width:100px;
height:100px;
background-color: blue;
position: absolute;
visibility: hidden;
}
和Javascript代碼:
var box = document.getElementById("box");
addEventListener('click', function(){
box.style.visibility="visible";
});
您可能會得到offsetX / Y或pageX / Y。 偏移量相對於目標元素,頁面-相對於文檔
var box = document.getElementById("box");
addEventListener('click', function(event){
box.style.visibility="visible";
box.left = event.pageX;
box.top = event.pageY;
});
您可以使用event.pageX
和event.pageY
來獲取相對於文檔左上角的光標位置。 請在下面嘗試:
addEventListener('click', createBox); function createBox(event) { var box = document.createElement('div'); box.className = 'box'; box.style.left = event.pageX + 'px'; box.style.top = event.pageY + 'px'; document.body.appendChild(box); }
.box { padding: 10px; margin-left: -10px; margin-top: -10px; background-color: blue; position: absolute; }
<p>Click anywhere!</p>
還要注意,如果要有多個框,最好使用類而不是ID。 ID旨在引用唯一元素,而類則旨在在多個元素之間共享。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.