如何通过javascript更改字体大小

时间:2017-05-24 21:26:12

标签: javascript html css

如何使用JavaScript更改left-column的字体大小?

<div id="left-column">
    <a href="">1</a><br>
    <a href="">2</a><br>
    <a href="">3</a><br>
    <a href="">4</a><br>
    <a href="">5</a><br>
    <a href="">6</a><br>
</div>

这是我到目前为止所做的:

<script>
    document.write(document.body.clientWidth);
    if (document.body.clientWidth > 400)
         document.getElementById('left-column').style.letterSpacing="0px";              
    }
 </script>

2 个答案:

答案 0 :(得分:1)

style对象使用与CSS相同的属性名称(减去hypen和camel大小写)。现在,font-size是一个&#34;继承&#34; property,表示在应用它时,该值也会应用于后代元素。因此,如果您愿意,可以将其应用于每个<a>元素,但您并不需要。您可以将它应用于它们的父元素。请记住,在这种情况下,所有后代元素都会受到影响,然后您必须重置您不想要受影响的元素上的字体。

&#13;
&#13;
document.querySelector("button").addEventListener("click", function(){

  var iw = window.innerWidth;
  
  document.getElementById("outputArea").textContent = "The usable width of the page is: " + iw + "px";

  if(iw > 400){
  
    // Get all the <a> elements that are children of the div
    var a = document.querySelectorAll("#leftcol > a");
  
    // loop through the colleciton of them and change their font size
    for(var i = 0; i < a.length; i++){
      a[i].style.fontSize = "3em"; 
    }
    
    // We could avoid getting all the <a> elements and looping through them one by one
    // and just do this:
    //   document.getElementById("leftcol").style.fontSize = "3em";
    // And that would affect the the elements within the #leftcol element.
  
  }

});
&#13;
<div id="outputArea"></div>
<div id="leftcol">
  <a href="">1</a><br>
  <a href="">2</a><br>
  <a href="">3</a><br>
  <a href="">4</a><br>
  <a href="">5</a><br>
  <a href="">6</a><br>
</div>
<button>Click Me</button>
&#13;
&#13;
&#13;

此外,除非您动态编写整个文档的DOM(通常是新窗口),否则不应使用document.write()。相反,将要输出的内容注入DOM中已有的元素。

答案 1 :(得分:1)

你应该使用CSS作为javascript的反对来控制你的字体大小根据页面宽度。最好的方法是使用媒体查询。有关详细信息,请参阅此页面。 https://www.w3schools.com/css/css3_mediaqueries_ex.asp

示例:

#leftcol{
    font-size: 20px;
}

@media screen and (max-width: 400px) {
    #leftcol {
        font-size: 12px;
    }
}

使用上面的示例,默认情况下字体大小为20px。当页面为400像素或更少时,它将减小到12。