<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.red{
background-color: red;
}
.green{
background-color: green;
}
</style>
</head>
<body>
<div id="div1" style="width: 300px;height: 300px;" class="green"></div>
</body>
</html>
<script>
var div1=document.getElementById("div1")
window.onresize = function(){
if(document.body.scrollWidth < 1024){
div1.classList.add("red");
div1.classList.remove("green")
}
else{
div1.classList.add("green");
div1.classList.remove("red");
}
}
</script>
效果:当屏幕宽度小于1024像素时,div背景颜色更改为红色。。