簡體   English   中英

為什么div不在我右鍵單擊的位置出現?

[英]Why the div doesn't appear where I right-click?

您能告訴我為什么div不在我點擊的位置出現嗎? 它僅顯示在左上方。

CSS:

#palette {
    display: none;
    width: 20px;
    height: 20px;
    background-color: red;
}

HTML:

<div id="palette"></div>

Javascript:

window.addEventListener('contextmenu', function(ev) {
  ev.preventDefault();
  document.getElementById('palette').setAttribute('left', ev.pageX);
  document.getElementById('palette').setAttribute('top', ev.pageY);
  document.getElementById('palette').setAttribute('position', 'absolute');
  document.getElementById('palette').style.display = 'block';
  return false;
}, false);

這是小提琴:

https://jsfiddle.net/0rL9neeL/

編輯:對不起,似乎我還沒有解釋問題:是的,這是右鍵單擊。 那就是div應該出現的地方。

您可以使用ev.clientXev.clientY作為坐標(以CSS像素返回相對於視口的坐標),然后使用javascript設置樣式。 您可以這樣操作:

 var element = document.getElementById('palette'); window.addEventListener('contextmenu', function(ev) { ev.preventDefault(); var x = ev.clientX; var y = ev.clientY; element.style.display = 'block'; element.style.left = x + "px"; element.style.top = y + "px"; return false; }, false); 
 #palette { display: none; width: 20px; height: 20px; background-color: red; position: absolute; } 
 <div id="palette"></div> 

代碼的問題在於,您正在使用setAttribute ,該屬性將屬性設置為DOM元素,而不是內聯CSS。

您正在將樣式設置為屬性,而實際上您應該在樣式對象上進行設置

 window.addEventListener('contextmenu', function(ev) { ev.preventDefault(); var style = { left: ev.pageX + 'px', top: ev.pageY + 'px', position: 'absolute', display: 'block' } Object.assign(document.getElementById('palette').style, style) return false; }, false); 
 #palette { display: none; width: 20px; height: 20px; background-color: red; } 
 <div id="palette"></div> 

您試圖設置元素本身的lefttoppositiondisplay屬性,而不是元素的style屬性(返回一個對象)。 另外,您需要將度量單位(在這種情況下為像素)附加到lefttop屬性的值top

 window.addEventListener('contextmenu', function(ev) { ev.preventDefault(); // Just get a reference to the DOM element once: var pal = document.getElementById('palette'); // Every DOM element has a style property, which exposes // a style object that, itself, exposes the various CSS // properties. Also, remember, CSS requires units of measurement pal.style.display = 'block'; pal.style.position = 'absolute'; pal.style.left = ev.pageX + "px"; pal.style.top = ev.pageY + "px"; // No need to return false here, that wasn't doing anything for you }); 
 #palette { display:none; width: 20px; height: 20px; background-color: red; } 
 <div id="palette"></div> 

右鍵單擊窗口將在左上角顯示紅色方塊。 您已經為上下文菜單添加了事件偵聽器,然后單擊鼠標右鍵。

我建議嘗試使用ev.clientXev.clientY來獲取鼠標坐標。

https://jsfiddle.net/0rL9neeL/3/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM