jQuery 根据屏幕分辨率在 javascript 中更改 CSS 类的高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15857077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:54:16  来源:igfitidea点击:

Change CSS Class height and width in javascript depending on screen res

jqueryscreen-resolution

提问by user2228313

I want the size of a div class 'content' to change depending on the size of the users' screen resolution.

我希望 div 类“内容”的大小根据用户屏幕分辨率的大小而改变。

So far Ive written this javascript

到目前为止,我已经写了这个 javascript

function resize()
{

    if ((screen.width>1024)) { $(".content").style.width = 560 + "px"; $(".content").style.height = 315 + "px" }
    if ((screen.width>1280)) { $(".content").style.width = 640 + "px"; $(".content").style.height = 360 + "px" }
    else { $(".content").style.width = 853 + "px"; $(".content").style.height = 480 + "px" }
};

and obviously in the html I have the class '.content'

显然在 html 我有类 '.content'

why is this code not working?

为什么这段代码不起作用?

回答by jszobody

Your specific issue here is that you are mixing jQuery and raw javascript.

您在这里的具体问题是您正在混合使用 jQuery 和原始 javascript。

To set the width of an element with jQuery, use the width()or css()method:

要使用 jQuery 设置元素的宽度,请使用width()css()方法:

$(".content").width(560);
$(".content").css('width',560);

Having said that, you may be better off looking at the browser size, not screen resolution. Shouldn't your content respond to the size of my browser, regardless of my screensize? I don't keep my browser fullscreen.

话虽如此,您最好查看浏览器大小,而不是屏幕分辨率。无论我的屏幕大小如何,您的内容都不应该响应我浏览器的大小吗?我不让浏览器全屏显示。

Lastly, look at css media querieseven to respond to the browser size. There are much better ways of doing this.

最后,查看css 媒体查询甚至响应浏览器大小。有很多更好的方法可以做到这一点。

回答by Giovanni

You can try and just use jQuery and CSS

你可以尝试只使用 jQuery 和 CSS

   function checkWindowSize() {  

    if ( $(window).width() > 1800 ) {  
        $('content').addClass('large');  
    }  
    else {  
        $('content').removeClass('large');  
    }  

}  

$(window).resize(checkWindowSize);  

For the CSS you would need to write it out like this:

对于 CSS,你需要这样写:

#content{  

}  

.large #content{  

}  

Here is a tutorial Source

这是一个教程来源