我想改变的css文件取决于如果用户是在移动或桌面上.我找不到任何实际工作的东西,所以我只是try 使用下面的js将用户重定向到一个带有diff css工作表的diff html页面.但我发现这超级低效.有没有人知道我怎样才能使css样式表根据页面中的屏幕宽度属性而改变?

<script type="text/javascript">
<!--
if (screen.width <= 699) {
document.location = "m_index.html";
}
//-->
</script>

       <!-- main css -->
       <link rel="stylesheet" href="master.css">
 
       <!-- CSS with media query -->
       <link rel="stylesheet"
             media="screen and (max-width: 360px)"
             href="small-screen.css">
       <link rel="stylesheet"
             media="screen and (min-width: 360px) and (max-width: 550px)"
             href="large-screen.css">

推荐答案

有响应式的设计是个好主意,但这是一种奇怪的方式.除非您使用JS来做这件事有一个非常好的理由,否则您可以用CSS来完成所有的工作,例如:https://www.w3schools.com/howto/howto_css_media_query_breakpoints.asp

在全屏模式下打开上面的代码片段,并调整窗口大小以查看演示.

有关更详细的文档,请参阅MDN page.

<!DOCTYPE html>
<!--copied from https://www.w3schools.com/howto/howto_css_media_query_breakpoints.asp-->
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.example {
  padding: 20px;
  color: white;
}
/* Extra small devices (phones, 600px and down) */
@media only screen and (max-width: 600px) {
  .example {background: red;}
}

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px) {
  .example {background: green;}
}

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {
  .example {background: blue;}
} 

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px) {
  .example {background: orange;}
} 

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px) {
  .example {background: pink;}
}
</style>
</head>
<body>

<h2>Typical Breakpoints</h2>
<p class="example">Resize the browser window to see how the background color of this paragraph changes on different screen sizes.</p>

</body>
</html>

Javascript相关问答推荐

将数据从strapi提取到next.js,但响应延迟API URL

使用print This时, map 容器已在LeafletJS中初始化

是什么原因导致此Angular 16电影应用程序中因类型错误而不存在属性?

有什么(最佳)方法可以从模块中获取脚本模块的多姆元素吗?

如何判断属于多个元素的属性是否具有多个值之一

从mat—country—select获取整个Country数组

将状态向下传递给映射的子元素

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

如何修复我的js构建表每当我添加一个额外的列作为它的第一列?

当运行d3示例代码时,没有显示任何内容

函数返回与输入对象具有相同键的对象

Chromium会将URL与JS一起传递到V8吗?

Ember.js 5.4更新会话存储时如何更新组件变量

如何确保预订系统跨不同时区的日期时间处理一致?

使用Document.Evaluate() Select 一个包含撇号的HTML元素

使用线性插值法旋转直线以查看鼠标会导致 skip

Node.js API-queryAll()中的MarkLogic数据移动

如何在加载页面时使锚定标记成为焦点

调试jQuery代码以获取所有行的总和(票证类型)

JavaScript structuredClone在Chrome/Edge中获得了非法调用,但在NodeJS中没有