我试图在点击的位置创建一个元素,我想出了下面的代码。但是点击页面没有任何反应,控制台也没有发现错误,为什么?
function create(event) {
var i = document.createElement("img");
i.setAttribute("id", "a");
i.src = *imagefile*;
i.position = "absolute";
i.style.left = event.clientX+'px';
i.style.top = event.clientY+'px';
}
document.addEventListener("click", create);
最佳答案
几个问题
- 您正在创建元素,但实际上并没有将它添加到任何地方。您需要确保使用
document.body.appendChild()
将其附加到 dom . i.position
应该是i.style.position
因为位置是 CSS 样式。- 有点吹毛求疵。 “id”属性在页面上应该是唯一的。单击多次将使这不是真的。在这种情况下根本不需要它。
function create(event) {
//Create the image
var i = document.createElement('img');
//Set the source of the image
i.src = 'https://www.mozilla.org/media/img/styleguide/identity/firefox/guidelines-logo.7ea045a4e288.png';
//Set CSS styles so it appears where you clicked (Top left corner)
i.style.position = 'absolute';
i.style.left = event.clientX + 'px';
i.style.top = event.clientY + 'px';
//Add it to the body of the document
document.body.appendChild(i);
}
//Main event listener for clicks
document.addEventListener('click', create);
关于javascript - 在点击的位置创建一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39969185/