亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在光標 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 關注
  • 115 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號