简体   繁体   English

如何在css中获取窗口大小

[英]How to get window size in css

I have a requirement which I want to make it to work with knockout.js. 我有一个要求,我想使其与淘汰赛.js一起使用。 I have a div with attribute binding. 我有一个属性绑定的股利。 when the user resizes the window, I am planning to set the attribute binding through css which I feel should update the view model. 当用户调整窗口大小时,我打算通过css设置属性绑定,我认为应该更新视图模型。

so can anyone tell me whether it is possible to get the screen size more than 500px and whether I can update the attribute binding through css? 所以谁能告诉我是否可以使屏幕尺寸大于500px,是否可以通过CSS更新属性绑定?

Please let me know if any further information is required on this regard. 请让我知道在这方面是否需要任何进一步的信息。

您无法使用CSS操作DOM元素属性,您将需要使用JavaScript!

use height and width and get height and width like below 使用高度宽度并获得高度和宽度,如下所示

$(window).height() ;

or 要么

   $(window).width();

if( $(window).height() >=500)
{...// apply your code
}

and set your css you can also use css 并设置您的CSS您也可以使用CSS

$("#divid").css({"height":"in px","width":"in px"});

or 要么

$("#divid").height(any number);
$("#divid").width(any number);

you cannot update an Attribute in DOM with CSS. 您无法使用CSS更新DOM中的属性。 what you can do is write a resize event to handle the change in size of the div and have the attribute changed based on that. 您可以做的是编写一个resize事件以处理div大小的更改,并根据该更改属性。

So basically, with event listeners you will be able to do that but definitely not with CSS :). 因此,基本上,使用事件监听器,您将能够做到这一点,但绝对不能使用CSS :)。

you can use javascript or jquery to achieve that. 您可以使用javascript或jquery来实现。

I guess this could be what you want: 我想这可能是您想要的:

@media (max-width: 500px) {
    #myDIv: { background-color: red; }
}

@media (min-width: 500px) {
    #myDIv: { background-color: blue; }
}

@media tag usually been used in responsive design. @media标签通常用于响应设计中。 With the @media tag, you don't need js to listen to resize window action. 使用@media标记,您不需要js来监听调整窗口大小的操作。

If I understand correctly your question, I think you can do it by css. 如果我正确理解了您的问题,我认为您可以通过CSS来解决。

If you just want to change some css value when you screen is under 500px and not above it. 如果您只想在屏幕低于500像素而不是高于500像素时更改某些CSS值。 This is totally possible by using media queries, here is a simple example: 这完全可以通过使用媒体查询来实现,这是一个简单的示例:

HTML 的HTML

put the following meta inside your page head (smartphones+tablets etc) 将以下meta放在您的页面头部(智能手机+平板电脑等)中

   <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

CSS 的CSS

.your-class {
          display: block;
          background:green;
          height: 100%;
          width: 50%;
        }



    @media screen and (max-width: 500px) {
/* This is only added when the size of the window is under 500px */
    .your-class {
              display: block;
              background: blue;
              height: 100%;
              width: 100%;
            }
      }

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

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