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类中,然后只是动态交换类而不是显式地执行每个样式属性。

更多相关文章

  1. 使用jackson json将属性添加到json字符串
  2. React组件的属性PropTypes
  3. Javascript XML DOM将属性设置为特定元素
  4. arcgis api for js入门开发系列十 自定义Navigation控件样式风格
  5. 为什么我收到此错误:“未捕获的TypeError:无法读取未定义的属性'标
  6. 打字稿:无法访问类属性[重复]
  7. 创建一个对外界只读的属性,但是我的方法仍然可以设置
  8. Javascript没有返回样式属性[重复]
  9. javascript小技巧&&JavaScript[对象.属性]集锦 [转载了多篇]

随机推荐

  1. Android优秀开源项目收集
  2. android SQLite 使用实例
  3. Android 基本空间划分
  4. android访问服务器端上传及服务器端接收
  5. Android中mpchartlib柱状图的详细属性以
  6. Android的android:clipChildren属性
  7. android 按钮点击的两种方法以及长按事件
  8. Android开发视频教程大总结—23部视频教
  9. Android版块开发资源大汇总
  10. 启动app闪屏问题以及Android自带主题