gpt4 book ai didi

javascript - 为一个 css 属性设置多个值

转载 作者:太空狗 更新时间:2023-10-29 15:48:42 24 4
gpt4 key购买 nike

是否可以为 CSS ID 上的单个属性设置两个值,例如

height: 12em; height: 12rem;

一个id?我知道可以使用 CSS 执行此操作,但我想通过 javascript 更改高度,并在一个属性上设置两个值,以便“em”作为不支持“rem”的浏览器的后备。

例子:

function updateHeight() {
var testElem = document.getElementById("testId");
testElem.style.height = "12em";
testElem.style.height = "12rem";
//testElem.style.height = "12em; 12rem;"; doesn't work, applies "12em"
}
#testId {
height: 8em;
height: 8rem;
background-color: black;
color: white;
}
<!DOCTYPE html>
<html>

<head>
<title>Test</title>
<meta charset="utf-8" />
</head>

<body>
<div id="testId">
BlaBla
</div>
<button onclick="updateHeight()">Bla</button>
</body>

</html>

最佳答案

您可以改用类

function updateHeight() {
var testElem = document.getElementById("testId");
testElem.classList.add('high');
}
#testId {
height: 8em;
height: 8rem;
background-color: black;
color: white;
}

#testId.high { /* remember that ID is more specific than class */
height: 12em;
height: 12rem;
}
<!DOCTYPE html>
<html>

<head>
<title>Test</title>
<meta charset="utf-8" />
</head>

<body>
<div id="testId">
BlaBla
</div>
<button onclick="updateHeight()">Bla</button>
</body>

</html>

或者如果值是动态的,您可能必须插入样式标签才能支持 CSS 级联

function updateHeight() {

var value = 12; // or something dynamic
var styles = '#testId {height: '+value+'em; height: '+value+'rem;}';
var tag = document.createElement('style');

tag.innerHTML = styles;

document.querySelector('head').appendChild(tag);

}
#testId {
height: 8em;
height: 8rem;
background-color: black;
color: white;
}
<!DOCTYPE html>
<html>

<head>
<title>Test</title>
<meta charset="utf-8" />
</head>

<body>
<div id="testId">
BlaBla
</div>
<button onclick="updateHeight()">Bla</button>
</body>

</html>

关于javascript - 为一个 css 属性设置多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com