查看: 45|回复: 0

Less中实现响应式设计的4种高效方案(手机、平板、电脑端)

[复制链接]

1

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2008-12-2
发表于 2025-4-24 11:39:00 | 显示全部楼层 |阅读模式

下是4种纯Less实现的响应式方案,均封装成可复用方法。

方案1:基础设备混合封装

// 定义设备断点变量
@mobile-max: 767px;
@tablet-min: 768px;
@tablet-max: 1024px;
@desktop-min: 1025px;

// 设备混合
.mobile(@rules) {
  @media (max-width: @mobile-max) {
    @rules();
  }
}
.tablet(@rules) {
  @media (min-width: @tablet-min) and (max-width: @tablet-max) {
    @rules();
  }
}
.desktop(@rules) {
  @media (min-width: @desktop-min) {
    @rules();
  }
}

// 使用示例
.header {
  font-size: 16px;
  
  .mobile({
    font-size: 14px;
    padding: 8px;
  });
  
  .tablet({
    font-size: 15px;
    padding: 12px;
  });
  
  .desktop({
    font-size: 18px;
    padding: 20px;
  });
}

方案2:参数化设备查询

// 参数化混合
.device(@type, @rules) {
  & when (@type = mobile) {
    @media (max-width: 767px) { @rules(); }
  }
  & when (@type = tablet) {
    @media (min-width: 768px) and (max-width: 1024px) { @rules(); }
  }
  & when (@type = desktop) {
    @media (min-width: 1025px) { @rules(); }
  }
}

// 使用示例
.navbar {
  height: 40px;
  
  .device(mobile, {
    height: auto;
    flex-direction: column;
  });
  
  .device(tablet, {
    height: 50px;
    padding: 0 15px;
  });
}

方案3:可配置断点混合

// 通用响应式混合
.responsive(@min, @max, @rules) {
  & when not (@min = 0) and not (@max = 0) {
    @media (min-width: @min) and (max-width: @max) { @rules(); }
  }
  & when (@min = 0) {
    @media (max-width: @max) { @rules(); }
  }
  & when (@max = 0) {
    @media (min-width: @min) { @rules(); }
  }
}

// 使用示例
.card {
  width: 100%;
  
  // 手机
  .responsive(0, 767px, {
    margin: 5px;
  });
  
  // 平板
  .responsive(768px, 1024px, {
    width: 48%;
    margin: 8px;
  });
  
  // PC
  .responsive(1025px, 0, {
    width: 23%;
    margin: 10px;
  });
}

方案4:设备方向增强版

// 带设备方向检测
.orientation(@device, @dir, @rules) {
  & when (@device = mobile) and (@dir = portrait) {
    @media (max-width: 767px) and (orientation: portrait) { @rules(); }
  }
  & when (@device = mobile) and (@dir = landscape) {
    @media (max-width: 767px) and (orientation: landscape) { @rules(); }
  }
  & when (@device = tablet) {
    @media (min-width: 768px) and (max-width: 1024px) { @rules(); }
  }
}

// 使用示例
.gallery {
  grid-template-columns: 1fr;
  
  .orientation(mobile, landscape, {
    grid-template-columns: repeat(2, 1fr);
  });
  
  .orientation(tablet, _, {
    grid-template-columns: repeat(3, 1fr);
  });
}

方案选择建议:

  1. 基础混合:适合明确的三段式断点需求
  2. 参数化混合:需要动态选择设备类型时使用
  3. 可配置断点:适合需要灵活调整断点的项目
  4. 方向增强:需要处理横竖屏差异时使用


来源:https://www.cnblogs.com/chatGPT-Last/p/18844302
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部