嗨,有没有更好的方法或(更干净的方法)来创建 dom 元素?比如数组之类的?
示例代码:
$hubbe.toolbarLeft = document.createElement('DIV');
$hubbe.toolbarLeft.setAttribute('id', 'toolbar-left');
$hubbe.toolbarLeft.style.width = '50px';
$hubbe.toolbarLeft.style.height = '100%';
$hubbe.toolbarLeft.style.position = 'fixed';
$hubbe.toolbarLeft.style.left = '0';
$hubbe.toolbarLeft.style.backgroundColor = 'grey';
$hubbe.toolbarLeft.style.color = 'white';
$hubbe.toolbarLeft.style.textAlign = 'center';
document.body.appendChild($hubbe.toolbarLeft);`
最佳答案
有一些库和框架可以帮助您实现这一点,例如 jQuery。如果您坚持使用普通 JavaScript,则可以通过 Object.assign()
批量设置属性来简化一点:
Object.assign($hubbe.toolbarLeft.style, {
width: '50px',
height: '100%',
position: 'fixed',
left: '0',
backgroundColor: 'grey',
color: 'white',
textAlign: 'center',
});
关于javascript - 清理 javascript dom 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50487036/