博客 / 詳情

返回

前端兼容阿拉伯頁面佈局RTL

在做國際化項目中可能會碰到阿拉伯語,阿拉伯語的文字排列方式是從右向左的,所以我們要將整體的佈局做調整。
很多css樣式都要調整,比如:margin-righttext-alignrightpadding-right等帶方向的,以及
文字的默認排列方式。

方法一:direction調整文字排列方向

css中有一個很有用的屬性:direction
direction CSS 屬性用於設置文本、表格列和水平溢出的方向。對於從右到左書寫的語言(如希伯來語或阿拉伯語),應將該屬性設置為 rtl;對於從左到右書寫的語言(如英語和大多數其他語言),則應將該屬性設置為 ltr
vue3項目中,應用到頁面上:

<script setup lang="ts">
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';

const themeStore = useThemeStore();
const { lang } = storeToRefs(themeStore);

const isRTL = computed(() => {
  return lang.value === 'ar'; // ar 阿拉伯語
});
</script>

<style lang="scss" scoped>
/* 在這裏添加全局樣式來控制整個頁面的佈局方向 */
* {
  unicode-bidi: embed;
  direction: v-bind('isRTL ? "rtl" : "ltr"') !important;
  text-align: v-bind('isRTL ? "right" : "left"') !important;
}
</style>

直接調整文字的排列方式即可。
這種方式快速有效,但是有缺陷,無法對UI組件庫內的文字生效,比如TDesign的表單文字。

方法二:vite-plugin-rtl-css

css+js的方式比較麻煩,現有的庫可以幫我們搞定

npm install vite-plugin-rtl-css --save-dev

這個庫非常簡單,集成只需要如下幾部:
1、vite.config.ts中配置

import { defineConfig } from 'vite';
import viteRtlCssPlugin from 'vite-plugin-rtl-css';

export default defineConfig({
  plugins: [
    viteRtlCssPlugin({
      fileNameMap: {
        '.css': '[name].rtl.css',
        '.min.css': '[name].rtl.min.css'
      },
      sourceMap: true,
      rtlcssConfig: {
        autoRename: true
      }
    });
  ]
});

配置説明:

  • fileNameMap 是一個可選參數,用於指定從文件擴展名到 RTL CSS 生成模板的映射。示例中顯示的是默認值。
  • sourceMap 是一個可選參數,用於指定是否應生成源映射。如果未指定,它將默認為您的 vite.config.ts 中的 build.sourcemap 。
  • rtlcssConfig 是一個可選參數,來自此插件用來配置 rtlcss 的 rtlcss 包。

vite-plugin-rtl-css會為每個CSS 文件生成對應的 RTL 版本,在 HTML 中根據 dir屬性自動加載對應的 CSS,示例如下:

<!-- 開發時 -->
<html dir="ltr"> <!-- 自動加載 index.css -->
<html dir="rtl"> <!-- 自動加載 index.rtl.css -->

<!-- 構建後 -->
<link rel="stylesheet" href="/assets/index.css" data-dir="ltr">
<link rel="stylesheet" href="/assets/index.rtl.css" data-dir="rtl">

2、根據語言動態切換html dir="ltr"屬性

<script setup lang="ts">
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';

const themeStore = useThemeStore();
const { lang } = storeToRefs(themeStore);

// 監聽 lang 變化,動態設置 html dir 屬性
watch(
  lang,
  newLang => {
    document.documentElement.dir = newLang === 'ar' ? 'rtl' : 'ltr';
  },
  { immediate: true }
);
</script>


其它方式
有很多現成的插件可以使用,我沒辦法全部試一遍,但網上有很多資料可以參考,可以根據實際需求使用,我這裏例舉一下:
postcss-rtlcssPostCSS 插件,使用 RTLCSS 自動構建包含從左到右(LTR)和從右到左(RTL)規則的層疊樣式表(CSS)
github:https://github.com/elchininet/postcss-rtlcss
rtlcss:RTLCSS 是一個用於將從左到右(LTR)級聯樣式表(CSS)轉換為從右到左(RTL)的框架。
github:https://github.com/MohammadYounes/rtlcss


參考資料:
direction:https://developer.mozilla.org/zh-CN/docs/Web/CSS/direction
vite-plugin-rtl-css:https://github.com/SmushyTaco/vite-plugin-rtl-css
documentElement:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/doc...
Web 端 RTL 適配實踐:https://juejin.cn/post/7343793872780296244

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.