gpt4 book ai didi

javascript - 如果屏幕尺寸太小,如何使用 JavaScript 函数更改 HTML 文件的背景颜色?

转载 作者:行者123 更新时间:2023-11-28 13:25:34 24 4
gpt4 key购买 nike

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

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

最佳答案

首先使用调整大小事件检查窗口大小 <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 - 如果屏幕尺寸太小,如何使用 JavaScript 函数更改 HTML 文件的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29515624/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com