1、直接修改
element.style.属性= "属性值"
-样式用驼峰命名法 background-color-->backgroundColor
2、修改类名
如果修改的样式比较多,可以直接另外写一个[或多个]类,用className覆盖
element.className="class1 class2 ..."
3、动态添加样式
const style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = hourPointer + minPointer + secondPointer;//自己要添加的样式(非固定)
document.getElementsByTagName('head')[0].appendChild(style);
1、样式不一定要一开始就有style标签,可以在JS里创建
2、JS里面写样式,一般是因为要用过一些非静态的变量,比如这里就是要写时钟,想要JS获取当前的时间
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
h = h > 12 ? h - 12 : h;
h = h * 30 - 90;
m = m * 6 - 90;
s = s * 6 - 90;
const hourPointer = `@keyframes hourPointer {
from {
transform: rotate(${h}deg);
}
to {
transform: rotate(${360 + h}deg);
}
} `
3、模板字符串,绝佳好用。
4、个人记录:
问题:一开始把<body>写在前面,<script>写在后面,结果document.querySelet和其他获取元素的方法拿不到元素,但是在控制台输入命令,却可以拿到元素。
方法:调整body和script位置就对了。因为html解析时,浏览器遇到script标签会暂停html,先去下载和解析script。