当您使用JavaScript编写element.style = "..."
时,会将style
属性添加到添加样式的元素。有没有style
属性,没有任何库的添加样式的方法吗?
如果可以提出一个以该元素为目标的选择器,另一个选择是附加一个包含该选择器的样式表:
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = 'div { color: blue; }';
<div>Some div</div>
如果允许您以某种方式更改元素,例如添加类或其他属性,那会更可靠:
const div = document.querySelector('div');
const className = `_${('' + Math.random()).slice(2)}`;
div.classList.add(className);
const styleTag = document.head.appendChild(document.createElement('style'));
styleTag.textContent = `.${className} { color: blue; }`;
<div>Some div</div>
使用JS,您可以将任何内容写入DOM,包括<style>
标签。因此,例如:
const el = document.getElementById('changeColor');
el.onclick = function(e) {
const s = document.createElement('style');
s.innerHTML = '.box { background-color: yellow; }';
document.querySelector('body').appendChild(s);
}
.box {
width: 150px;
height: 150px;
background-color: red;
color: white;
padding: 20px;
}
#changeColor {
margin: 10px 0;
}
<body>
<button type="button" id="changeColor">Change It</button>
<div class="box">This is a box</div>
</body>
styles
标签内添加CSS类DOMContentLoaded
事件将一个类添加到元素中>]setAttribute
方法将CSS类添加到标签元素中>]
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Example</title>
<style>
.styles {
color: red;
}
</style>
</head>
<body>
<p>Hello there</p>
<script>
let paragraph = document.querySelector("p")
document.addEventListener("DOMContentLoaded", () => {
paragraph.setAttribute("class", "styles")
})
</script>
</body>
</html>