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

我如何才能创建一个新元素并将其放置在鼠标/光标所在的位置?我下面有一些示例代码:


<div id = "adivthing></div>


<script>

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

document.getElementById("adivthing").appendChild(newthing); 

</script>


繁花如伊
浏览 62回答 1
1回答

冉冉说

如果您在元素上使用position: fixed或position: absolutestyle 属性newthing,则可以使用left和top属性在框周围移动元素。如果您从触发事件(例如单击)获取鼠标坐标,则可以将适当的left和添加top到您的元素中。下面的例子:function createInput(event){&nbsp; var newthing = document.createElement("input");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; document.getElementById("adivthing").appendChild(newthing); // Your existing code&nbsp; // get the coordinates of the mouse&nbsp; var x = event.clientX;&nbsp; &nbsp; &nbsp;// get the horizontal coordinate&nbsp; var y = event.clientY;&nbsp; &nbsp;// get the vertical coordinate&nbsp; // position newthing using the coordinates&nbsp; newthing.style.position = "fixed"; // fixes el relative to page. Could use absolute.&nbsp; newthing.style.left = x + "px";&nbsp; newthing.style.top = y + "px";}/* Optional - Making new things more obvious in the pen */input{&nbsp; &nbsp; height: 10px;&nbsp; &nbsp; width: 50px;&nbsp; &nbsp; background: red;}#adivthing{&nbsp; &nbsp; height: 600px;&nbsp; &nbsp; width: 600px;&nbsp; &nbsp; background: blue;}<!-- Onclick event added to your existing markup --><div id="adivthing" onclick="createInput(event)"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5