当窗口变得太小时如何更改HTML元素?

时间:2014-12-10 15:11:50

标签: javascript html resize

所以这就是我所拥有的:

<!DOCTYPE html>
<html>
<head>
    <title>Fonts!</title>
    <link rel="stylesheet" href="fonts.css">
</head>
<body>
    <h1 id="Hagin">Hello.</h1>
    <h2 id="Hagin2">Goodbye.</h2>

    <p class="Glober">Hello. This is a paragraph. It is meant to test this font. What do you think? Do you like this font? I think I do, although I'm not sure. That's why I'm writing this paragraph. Eh? Bigger you say? I agree. Let's make it bigger. Yeah, you know what, I'm using this. Allong with that Hagin thing. Some sexy shit.</p>

    <script type="text/javascript">
    window.onresize = function() {
        var width = window.innerWidth;
        var h1 = document.getElementById("Hagin");
        var h2 = document.getElementById("Hagin2");

        if (width < 1000) {
            h1.fontFamily = "Sans";
        }
    };
    </script>
</body>
</html>

现在,当窗口宽度低于1000px时,我只是想让字体更改为Sans。它不起作用......没有任何反应。控制台中未报告任何错误。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您需要使用具有该属性的style对象。您目前正在做的是将名为fontFamily的属性附加到h1

if (width < 1000) {
    h1.style.fontFamily = "Sans";
}

答案 1 :(得分:0)

您需要使用媒体查询创建css案例。查阅 - link

答案 2 :(得分:0)

这就是CSS媒体查询的用途。在现有CSS的末尾(或之后)添加:

@media screen and (max-width: 999px) {
  #Hagin {
    font-family: Sans; 
  }
}

或者,如果您希望将其应用于所有 h1标记:

@media screen and (max-width: 999px) {
  h1 {
    font-family: Sans; 
  }
}