簡體   English   中英

如何使用JavaScript更改文本的字體粗細

[英]How to change font-weight of a text using JavaScript

我有一個看起來像這樣的按鈕:

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”變為正常。 當我再次點擊時,我希望“黑暗”是大膽的,“光”是正常的。 但我不能讓它發揮作用。 有趣的是,我可以創建一個功能相同的功能,但顏色而不是字體重量。

有效的代碼但改變顏色而不是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(好吧,我沒試過8)。 但是,在Opera上, fontWeight700而不是bold (這並非完全不合理)。 所以,如果你在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";
    }
  }

})();

...但當然有很多選項( data-*屬性等)。

為什么不用普通字體創建2個類,用粗體字創建一個類,根據分配給元素的類分配/刪除這些類? jQuery的hasClass()addClass()removeClass()有很大的幫助這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM