我有一个看起来像这样的按钮:
Theme: Dark/Light
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”变为正常.当我再次点击时,我希望“黑暗”是大胆的,“光”是正常的.但我不能让它发挥作用.有趣的是,我可以创建一个功能相同的功能,但颜色而不是字体重量.
有效的代码但改变颜色而不是font-weight:
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";
}}
我认为代码会做同样的事情,但使用font-weight:
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";
}}
谢谢!
编辑:
现在这次我尝试它似乎也适合我.我想某处有一个错字.
谢谢大家的回答,我很抱歉,我花了你的时间!
解决方法:
它在Chrome,Firefox和IE6-9上有works for me(好吧,我没试过8).但是,在Opera上,fontWeight的结果是700而不是粗体(这并非完全不合理).所以,如果你在Opera遇到麻烦,那可能就是原因.
因此,您可能需要维护一个与元素的style.fontWeight属性分开的标志.一种方法是这样的:
(function() {
var lightBold = false;
// Export just the theme function out of the scoping function
window.theme = theme;
function theme(){
var dark = document.getElementById('dark');
var light = document.getElementById('light');
lightBold = !lightBold;
if(lightBold){
light.style.fontWeight="bold";
dark.style.fontWeight="normal";
}else{
dark.style.fontWeight="bold";
light.style.fontWeight="normal";
}
}
})();
标签:javascript,css
来源: https://codeday.me/bug/20190530/1184383.html