我在我的 localstorage 中存储了一个值,并基于该值我想在模板文字符号中决定样式。
这里我有一些变量:
var right = localStorage.getItem("shareBarPosition") === "right";
var posRight = `#socialShare {
left: auto;
right: 0 !important;
}`;
var posLeft = `#socialShare {
left: 0 !important;
right: auto;
}`;
我想在这样的模板文字符号中使用它:
document.querySelector("#shareButton-code").innerHTML += `<style>
/* Button specific styling */
${right ? posRight : posLeft}
</style>`
但这将始终显示 posRight 样式。这是为什么?
最佳答案
我必须将 innerHTML +=
更改为 innerHTML =
document.querySelector("#shareButton-code").innerHTML = `<style>
/* Button specific styling */
${!right ? posLeft : posRight}
</style>`
关于javascript - 在 javascript 模板文字中使用条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51841816/