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

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

在特定位置插入 div

在特定位置插入 div

回首憶惘然 2023-07-29 16:52:02
我有一個包含很多 div 的頁面,例如表單填寫頁面(不是靜態固定的,而是動態生成的)。在這里,我需要創建一個新的 div 并將其放置在特定的 [x,y] 位置,該位置也不是固定的,但在渲染時會動態變化。所以我的問題是如何使用 javascript/jquery 將新創建的 div 放置在特定的 [x,y] 位置?我正在嘗試這樣,但 div 沒有出現:const showFormFieldErrorMessage = function (data, message) {    const errorMsg = message || 'This field is required.';    const errorElem = document.createElement('div');    errorElem.style.backgroundColor = '#ff0000';    errorElem.innerHTML = errorMsg;    errorElem.style.top = `${(data && data.position && data.position.posy) ? data.position.posy : '0'}px`;    errorElem.style.left = `${(data && data.position && data.position.posx) ? data.position.posx : '0'}px`;    errorElem.zIndex = 900;};注意:參數數據是我在運行時獲取位置詳細信息的地方。提前致謝!!
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

如果您想將新創建的 div 添加到文檔正文中,可以使用以下命令:


const showFormFieldErrorMessage = function (data, message) {

    const errorMsg = message || 'This field is required.';

    const errorElem = document.createElement('div');

    errorElem.style.backgroundColor = '#ff0000';

    errorElem.innerHTML = errorMsg;

    errorElem.style.top = `${(data && data.position && data.position.posy) ? data.position.posy : '0'}px`;

    errorElem.style.left = `${(data && data.position && data.position.posx) ? data.position.posx : '0'}px`;

    errorElem.style.position = 'absolute';

    errorElem.zIndex = 900;


    document.body.appendChild(errorElem);

};

您可以使用以下方法將新元素添加到文檔正文:


document.body.appendChild(errorElem);

注意:確保將位置設置為“絕對”,errorElem否則頂部和左側屬性將不起作用。


查看完整回答
反對 回復 2023-07-29
?
狐的傳說

TA貢獻1804條經驗 獲得超3個贊

思路如下:

  1. 您的 div 需要首先定位,即設置style.position元素的屬性。

  2. 設置元素的style.top,style.left屬性以將元素放置在特定坐標上。

這是工作示例:

function addToCoordinates() {

    var div1 = document.createElement('div');

    var x_pos = '100px', y_pos = '100px';


    div1.id = 'div1';

    div1.style.height = "200px";

    div1.style.width = "200px";

    div1.style.backgroundColor = "#1abc9c";

    div1.style.position = "absolute";

    div1.style.left = x_pos;

    div1.style.top = y_pos;


    document.body.appendChild(div1);

}

<button onclick="addToCoordinates()">Add div on a particular position</button>


查看完整回答
反對 回復 2023-07-29
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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