【发布时间】:2017-02-08 12:40:46
【问题描述】:
我有一个如下所示的按钮:
HTML:
<button type="button" id="top_skin" onclick="theme()">Theme: <span id="dark">Dark</span>/<span id="light">Light</span></button>
CSS:
#top_skin{display:inline;
float:right;
margin:5px 15px 5px 5px;
padding: 0px 5px 0px 5px;
height:20px;
min-width:140px;
background:grey;
cursor:pointer;
border-radius:5px;
overflow:hidden;
}
#dark{font-weight:bold;}
我希望 JavaScript 切换单词“Dark”和“Light”的字体粗细,这样当我单击按钮时,单词“Light”变得粗体,而“Dark”变得正常。当我再次单击时,我希望“暗”为粗体,“亮”为正常。但我不能让它工作。有趣的是,我可以创建一个函数来做同样的事情,但使用颜色而不是字体粗细。
有效但改变颜色而不是字体粗细的代码:
function theme(){
var dark = document.getElementById('dark');
var light = document.getElementById('light');
if(light.style.color !== "red"){
light.style.color="red";
dark.style.color="black";
}else{
dark.style.color="red";
light.style.color="black";
}}
我认为会做同样事情的代码,但使用字体粗细:
function theme(){
var dark = document.getElementById('dark');
var light = document.getElementById('light');
if(light.style.fontWeight !== "bold"){
light.style.fontWeight="bold";
dark.style.fontWeight="normal";
}else{
dark.style.fontWeight="bold";
light.style.fontWeight="normal";
}}
谢谢!
编辑:
现在,当我尝试它时,它似乎对我来说也很好用。我想某处有错字。 谢谢大家的回答,很抱歉耽误了您的时间!
【问题讨论】:
-
我希望如果您使用调试器进行操作,您可以弄清楚。在 2012 年,确实有 no excuse 不使用调试器来调试您的客户端代码。 :-)
-
在 Firefox、Chrome、IE7 甚至 IE6 中为我工作(!):jsbin.com/eyabor
标签: javascript css