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>
- 1 回答
- 0 關注
- 115 瀏覽
添加回答
舉報