如果使用 javascript 函数屏幕尺寸太小,我将如何更改 HTML 文件的背景颜色? [英] How would I change the background color of an HTML file if the screen size is too small using a javascript function?

查看:23
本文介绍了如果使用 javascript 函数屏幕尺寸太小,我将如何更改 HTML 文件的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用 javascript 函数屏幕尺寸太小,我将如何更改 HTML 文件的背景颜色?例如,我需要将 HTML 文件的背景设为灰色,但如果窗口大小小于 600 像素,则它会变为红色.我是用 CSS 做的,但需要用 java 脚本来做.这是我在 CSS 中的内容

How would I change the background color of an HTML file if the screen size is too small using a javascript function? For example I need the background of my HTML file to be gray but if the window size is less than 600px it turns red. I did it with CSS but need to do it in java script. Here is what I have in CSS

<style> 
body {     
  background-color: gray; 
}  
@media screen and (max-width: 600px) {     
  body {        
    background-color: red;     
  } 
} 
</style>

推荐答案

首先使用resize事件检查窗口大小

First of all check window size using resize event <body onresize="changeColor()">

添加以下函数来实现您的逻辑

Add following function to implement your logic

<script>
//Check if window width is less than or equal to 600,then change bg
function changeColor() {
    var w = window.outerWidth;
    if(w<=600)
    document.body.style.backgroundColor = "red";
}
</script>

这篇关于如果使用 javascript 函数屏幕尺寸太小,我将如何更改 HTML 文件的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆