繁体   English   中英

如何使用JavaScript更改DOM元素,具体取决于客户端的屏幕尺寸

[英]How to change DOM elements, using javascript, depending on the screen size of a client

我正在使用此事件滑块,该滑块具有3个带有左右滚动按钮的帖子。 但是我是自适应设计的新手,一旦屏幕尺寸减小到1000px,我想更改整个内容,包括DIV中的所有元素。 请帮助我提出一些想法。

在CSS中,使用最大宽度为1000px的媒体查询。 在媒体查询内部应用一些CSS,这些CSS仅在<= 1000px的设备上生效。

@media(max-width:1000px){
 /* So  in here you might want to apply some css to stack your posts one after the other and to hide your left and right scroll buttons*/
}

您可以在CSS中定义类似的内容

div {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

或者您可以使用媒体在CSS文件中设置字体大小

@media(max-width:767px) {
    body {
        font-size: 10px;
    };
}

@media(min-width:768px) {
    body {
        font-size: 11px;
    };
}

@media(min-width:992px) {
    body {
        font-size: 12px;
    };
}

@media(min-width:1200px) {
    body {
        font-size: 13px;
    };
}

然后在调整浏览器大小或根据分辨率按比例调整每个要调整字体大小的元素上的字体大小。

例如:如果要在h1上调整字体大小

h1 {
   font-size: 150%;
}

它会按您希望的那样工作。

编辑:我认为您需要根据台式机,平板电脑和移动设备调整屏幕的尺寸,如果有的话,这可能有所帮助

假设此HTML:

<div id="some_container">
    <nav id="n1">
        <ul>
            <li>1</li>
            <li>2</li>
        </ul>
    </nav>
    <p>Some Text</p>
    <nav id="n2">
        <ul>
            <li>1</li>
            <li>2</li>
        </ul>
    </nav>
</div>

您只需要以下CSS:

#n1{
    display:none;
}

@media only screen 
and (max-width : 1000px) {
    #n1{
        display:block;
    }
    #n2{
        display:none;
    }
}

这种方法的优点在于它的可伸缩性。 需要在其他页面上使用此“效果”吗? 您只需要编辑[u]那个[/ u]页面。 不用搞乱JavaScript,对新类/案例进行硬编码。

使用CSS媒体查询而不是使用Javascript。 更少的代码,更高效

@media (min-width: 1001px) {
  #yourDiv {
     /*Add css property to your div when its 1001px or more*/
  }
}

 @media (max-width: 1000px) {
   #yourDiv {      
      /*Add css property to your div when its 1000px or less*/
   }
 }

检查此链接以获取更多示例: http : //www.w3schools.com/css/css3_mediaqueries_ex.asp

看看下面使用CSS媒体查询的示例,它可能会对您有所帮助。

 <style> @media(min-width:1000px) { .hide-on-desktop { display:none; }; } @media(max-width:999px) and (min-width:767px) { .hide-on-laptop { display:none; }; } @media(max-width:766px) { .hide-on-mobile { display:none; }; } </style> 
 <div class="hide-on-desktop hide-on-laptop"> for mobile </div> <div class="hide-on-desktop hide-on-mobile"> for laptop </div> <div class="hide-on-laptop hide-on-mobile"> for desktop </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM