简体   繁体   English

如何在 position XY 处的 DIV 中插入元素

[英]How to insert an element in DIV at position X Y

I am trying to create a webpage where users can insert a pin (like google map) in between the text using context menu.我正在尝试创建一个网页,用户可以在其中使用上下文菜单在文本之间插入一个图钉(如谷歌地图)。

My problem is that i do not know how to insert the pin at the exact position.我的问题是我不知道如何将引脚插入确切的 position。 Using the DOM I can arrive only to the nearest DIV (by using this ) but a DIV contains a lot of text and the PIN has to be positioned next to the text.使用 DOM 我只能到达最近的 DIV(通过使用this ),但是 DIV 包含大量文本,并且 PIN 必须位于文本旁边。

I can obtain the position of the mouse click using pageX and pageY but dont know how to insert an element at that position.我可以使用 pageX 和 pageY 获得鼠标单击的 position,但不知道如何在该 position 处插入元素。 I tried in JQuery: insertAfter, prepend, append but not getting the desired result.我试过 JQuery: insertAfter, prepend, append 但没有得到想要的结果。

Any idea how to solve this problem.任何想法如何解决这个问题。

regards, choesang tenzin问候, Choesang Tenzin

 $("#Content").rightClick( function(e) {

    $("<div class='pin'/>").insertAfter(this); 
 });    
$("#Content").rightClick( function(e) {
        var myTop = ...;
        var myRight= ...;
        $("<div class='pin' style='position:absolute; top: ' + myTop +'px; right: ' + myRight + 'px;/>").insertAfter(this); 
 });

sorry, i don't remember how to get x and y from the e parameter.抱歉,我不记得如何从 e 参数中获取 x 和 y 了。 Also, you will need to convert x,y of mouse click to x,y relative to #content element.此外,您需要将鼠标单击的 x,y 转换为相对于 #content 元素的 x,y。

Set the style position:relaitve;设置样式position:relaitve; on the containing div, so that it becomes a layer.在包含的 div 上,使其成为一个图层。 That way it works as origin for the absolutely positioned elements inside it.这样它就可以作为其中绝对定位元素的原点。

Thanks alot for all your ideas.非常感谢你的所有想法。 I have come up with another way to do it.我想出了另一种方法来做到这一点。 I am using the "RANGE" to insert directly into the clicked zone (div) and not after or before it and adding z-indexes.我正在使用“RANGE”直接插入到单击区域(div)中,而不是在它之后或之前并添加 z-indexes。 The positive points with this is:这样做的好处是:

  1. It is really into the text and not as a layer它真的在文本中而不是作为图层
  2. texts flow around the pin (text makes space for the pin)文本在引脚周围流动(文本为引脚腾出空间)

     $("div").click( function(e) { //the following works only for FF at the moment var range = window.getSelection().getRangeAt(0); var pin = document.createElement('img'); pin.setAttribute('src','pin_org.png'); pin.setAttribute('class','pin'); range.insertNode(pin); }); $("img.pin").live( 'mouseover', function () { alert("hovered;!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM