为了账号安全,请及时绑定邮箱和手机立即绑定

如何在光标 DOM 上创建新元素

如何在光标 DOM 上创建新元素

繁花如伊 2023-10-04 15:52:03
我如何才能创建一个新元素并将其放置在鼠标/光标所在的位置?我下面有一些示例代码:<div id = "adivthing></div><script>var newthing = document.createElement("input");                document.getElementById("adivthing").appendChild(newthing); </script>
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

如果您在元素上使用position: fixed或position: absolutestyle 属性newthing,则可以使用left和top属性在框周围移动元素。


如果您从触发事件(例如单击)获取鼠标坐标,则可以将适当的left和添加top到您的元素中。


下面的例子:


function createInput(event){

  var newthing = document.createElement("input");                

  document.getElementById("adivthing").appendChild(newthing); // Your existing code



  // get the coordinates of the mouse

  var x = event.clientX;     // get the horizontal coordinate

  var y = event.clientY;   // get the vertical coordinate


  // position newthing using the coordinates

  newthing.style.position = "fixed"; // fixes el relative to page. Could use absolute.

  newthing.style.left = x + "px";

  newthing.style.top = y + "px";

}

/* Optional - Making new things more obvious in the pen */

input{

    height: 10px;

    width: 50px;

    background: red;

}


#adivthing{

    height: 600px;

    width: 600px;

    background: blue;

}

<!-- Onclick event added to your existing markup -->

<div id="adivthing" onclick="createInput(event)"></div>


查看完整回答
反对 回复 2023-10-04
  • 1 回答
  • 0 关注
  • 57 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信