繁体   English   中英

如何将元素附加到正文?

[英]How to append element to body?

我目前使用以下代码将 div 附加到正文:

$("body").append('<div class="tooltip" id="op" style="position: absolute; z-index: 999; height: 16px; width: 16px; top:70px"><span>Test</span></div>');

我怎么能像上面一样做但不使用jQuery

在纯 Javascript 中,它会更冗长一点:

 var div = document.createElement('div'); div.className = 'tooltip'; div.id = 'op'; div.style.cssText = 'position: absolute; z-index: 999; height: 16px; width: 16px; top:70px'; div.innerHTML = '<span>Test</span>'; document.body.appendChild(div);

我真的很喜欢所有现代浏览器的 insertAdjacentHTML 方法——并且也支持旧浏览器。

参考: http : //updates.html5rocks.com/2011/08/insertAdjacentHTML-Everywhere

用法:

var html = '<div class="tooltip" id="op" style="position: absolute; z-index: 999; height: 16px; width: 16px; top:70px"><span>Test</span></div>';
document.body.insertAdjacentHTML('beforeend', html);

你可以用 DOM 做很多事情! 您可以通过这种方式操作简单的 html!

查看 W3 网站: http : //www.w3schools.com/js/js_htmldom.asp

一个更简单的方法是

var t = document.createElement('div')
t.innerHTML = '<div class="tooltip" id="op" style="position: absolute; z-index: 999; height: 16px; width: 16px; top:70px"><span>Test</span></div>';
document.body.insertAdjacentElement("beforeend", t);

在此处阅读有关 insertAdjacentElement 的信息 - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM