繁体   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