rym*_*ymn 1 javascript greasemonkey
我正在编写一个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);
}
Run Code Online (Sandbox Code Playgroud)
正如你在我的示例代码中看到的那样,我反复写了很多次.你有技术可以避免这种混乱吗?只是为了优雅.
谢谢 -
伙计们,这是减少的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
大声笑,这当然看起来更好