你如何组织Javascript verboseness?
16lz
2021-01-22
I am coding a GM script, and one thing I realised that I'm doing repeatedly is doing the same code over and over again. Specifically, the style property.
我正在编写一个GM脚本,有一件事我意识到我反复做的是一遍又一遍地做同样的代码。具体来说,是样式属性。
function createButton() {
var a = document.createElement('a');
a.href = '#';
a.innerHTML = 'Print Topic';
a.style.position = 'absolute';
a.style.right = '3em';
a.style.top = '6em';
a.style.fontFamily = 'Arial,Helvetica,sans-serif';
a.style.fontWeight = 'bold';
a.style.fontSize = '125%';
a.style.background = '#777777 none repeat scroll 0 0';
a.style.color = 'white';
a.style.padding = '6px 12px';
document.body.insertBefore(a, document.body.lastChild);
}
As you can see in my sample code, I repeatedly wrote a.style a lot of times. Do you have techniques that you use to avoid this mess? Just for the sake of gracefulness.
正如你在我的示例代码中看到的那样,我反复多次写过a.style。你有技术可以避免这种混乱吗?只是为了优雅。
THANKS --
Guys, here's the reduced code:
伙计们,这是减少的代码:
function createButton() {
var a = document.createElement('a');
var css = document.createElement('style');
css.type = 'text/css';
css.innerHTML = '#prt { position:absolute; right:3em; top: 6em; font-family: Arial,Helvetica,sans-serif; font-weight:bold; font-size:125%; background: #777777 none repeat scroll 0 0; color: white; padding: 6px 12px;}'
a.href = '#';
a.innerHTML = 'Print Topic';
a.id = 'prt';
document.body.insertBefore(a, document.body.lastChild);
document.body.appendChild(css);
}
LOL, that certainly looks better
大声笑,这当然看起来更好
6 个解决方案
#1
Put the style attributes into CSS classes, then just dynamically swap the classes instead of doing each style attribute explicitly.
将样式属性放入CSS类中,然后只是动态交换类而不是显式地执行每个样式属性。
更多相关文章
- 使用jackson json将属性添加到json字符串
- React组件的属性PropTypes
- Javascript XML DOM将属性设置为特定元素
- arcgis api for js入门开发系列十 自定义Navigation控件样式风格
- 为什么我收到此错误:“未捕获的TypeError:无法读取未定义的属性'标
- 打字稿:无法访问类属性[重复]
- 创建一个对外界只读的属性,但是我的方法仍然可以设置
- Javascript没有返回样式属性[重复]
- javascript小技巧&&JavaScript[对象.属性]集锦 [转载了多篇]