如果使用javascript函数屏幕太小,我该如何更改HTML文件的背景色

How would I change the background color of an HTML file if the screen size is too small using a javascript function?

本文关键字:何更改 HTML 文件 背景色 javascript 函数 屏幕 如果      更新时间:2023-09-26

如果使用javascript函数屏幕太小,我该如何更改HTML文件的背景色?例如,我需要我的HTML文件的背景是灰色的,但如果窗口大小小于600px,它就会变成红色。以下是我在CSS 中的内容

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

首先使用resize事件检查窗口大小<body onresize="changeColor()">

添加以下功能来实现您的逻辑

<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:-

if (window.screen.availWidth < 600) {
      document.body.style.background="#FF0000"
}

对于jQuery,使用$( window ).width();方法。

您可能想要附加到全局window对象的onresize事件。(https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onresize)。

然后,您可以检查窗口大小并采取相应的行动。(https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth)。

例如

window.onresize = function(){
 if (window.innerWidth < 600){
  // set colors
 } else {
  // set other colors
 }
}
  $(document).ready(function(){
      if($(window).width() < 600){
        $('body').css('background-color','red');
    }else{
     $('body').css('background-color','grey');
      }
    });

既然所有主流浏览器都支持媒体查询,那么在JavaScript中做这样的事情真的没有意义,但如果你不想同时针对旧浏览器,这将起到作用:

var backgroundColorCheck = function() {
  if ( window.screen.availWidth <= 600 ) {
    document.body.style.backgroundColor = 'red';
  }
  else {
    document.body.style.backgroundColor = 'blue';
  }
}; 
// bind our backgroundColorCheck function to the resize event:
window.onresize = backgroundColorCheck;
// call backgroundColorCheck function to make an initial check of the width:
backgroundColorCheck();

这应该能奏效。一旦页面加载,以及每当用户更改窗口大小时,它都会启动。

document.onload = checkWidth();
window.onresize = checkWidth();
function checkWidth() {
    if (window.innerWidth < 600) {
        document.body.style.backgroundColor = "red";
    } else {
        document.body.style.backgroundColor = "gray";
    }
}

如果您使用jquery,您可以执行

function resize(){
   if($(window).width() < '600'){
         $('body').css('background','#000');
     }
     else{
          $('body').css('background','#fff');
     }
};
$(document).ready(resize);
$(window).resize(resize);