【问题标题】:How to change font-weight of a text using JavaScript如何使用 JavaScript 更改文本的字体粗细
【发布时间】: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


【解决方案1】:

它在 Chrome、Firefox 和 IE6-9 上为 works for me(好吧,我没有尝试 8)。但是,在 Opera 上,fontWeight700 而不是bold (这并非完全不合理)返回。因此,如果您在 Opera 上遇到问题,这可能就是原因。

因此,您可能需要维护一个与元素的 style.fontWeight 属性分开的标志。一种方法是这样的:

Live copy | Live copy source

(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";
    }
  }

})();

...但当然有很多选择(a data-* attribute 等)。

【讨论】:

    【解决方案2】:

    为什么不创建 2 个类,一个使用普通字体,一个使用粗体字体,然后根据分配给元素的类来分配/删除这些类? jQuery 的 hasClass()addClass()removeClass() 在这里有很大的帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2018-05-07
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2014-07-16
      相关资源
      最近更新 更多