RTL适配实践

2019-06-03  本文已影响0人  一张白纸清

背景

思考

对于rtl网站的适配,这里有两种方案参考
1、direction 布局方案
2、transform镜像翻转方案

direction 布局方案

.test: {
  direction: rtl;
  margin-right: 10px;
  float: left;
}

通过rtlcss模块处理后

.test: {
  direction: ltr;
  margin-left: 10px;
  float: right;
}

最后通过一套代码编译成一套 html,多套 css,一套 js 文件,区分国家用户来进行访问。

transform镜像翻转方案

transform镜像翻转通过一套html,一套css,一套js文件既可完成ltr和rtl适配
下面介绍一下我在项目中的实现(react中台项目)

封装一个FlipBox组件用来包裹需要翻转的text和img(FlipBox 可以替换页面中的span标签,img通过div包裹),获取url中的locale字段,locale字段来判定LTR布局还是RTL布局。

const locale = localeDeal() || 'en-US';
export const FlipBox = ({ children, ...props }) => {
  if(typeof children === 'string') {
      return (
        <span
          {...props}
          style={{ transform: (locale === 'he-IL' || locale === 'ar-EG') ? 'scaleX(-1)' : 'none' }}
        >{ children }</span>
      )
  }
  return (
    <div
      {...props}
      style={{
      display: 'inline-block',
      transform: (locale === 'he-IL' || locale === 'ar-EG') ? 'scaleX(-1)' : 'none',
    }}
    >
      { children }
    </div>
  )
}
if(locale === 'he-IL' || locale === 'ar-EG') {
  const domeRoot = document.getElementById('root');
  domeRoot.style.transform="scaleX(-1)";
}
    <div className={styles.formItemTitle}>
      <FlipBox>我的滑板鞋,时尚时尚最时尚 {''}</FlipBox>
      <FlipBox>
            <img className={styles.modalImg} src={imgList.bills} alt="" />
      </FlipBox>
    </div>

这种方式可以实现图片和文字的正常显示。看似结束了,好像完美解决了。但是我们忽略了input这个标签
input经过root的transform翻转和自身的transform翻转后会回复到之前的状态,简单来说负负的正。还是LTR布局格式,所以还要借助direction特定对input(这里的input是antd中的,原理一样)设定一个rtl来适配。

  export const isLeftType = locale !== 'he-IL' && locale !== 'ar-EG';
    <FlipBox>
      <input 
        dir={isLeftType ? "ltr" : "rtl"}
        value={value}
        onChange={onChange}/>
    </FlipBox>

这里可以解决input的RTL适配。
当前页面为状态页面的时候,可能存在LTR布局和RTL布局无差异的情况,这个时候可以通过transform: scaleX(-1)把整个页面翻转回来,这样可以做到减少入侵代码,提高代码的可读性。
transform: scaleX(-1)方案来解决RTL布局的适配优缺点都很明显
优点:
1、transform翻转是兼容原来的css和js逻辑的。翻转后margin-left: 10px;在浏览器的理解下是向右的,而direction 方案只是针对 CSS,JS 逻辑需要调整兼容。
2、transform不需要考虑 CSS 命名,CDN 部署等一系列工程问题,因为它是划分 CSS 作用域的方式,针对 LTR/RTL 布局进行隔离适配。
3、内嵌样式 transform 方案也可以很好地做到兼容,而 direction 方案是针对 CSS 文件的,如果要针对 html 文件则需要另外额外的工作。
缺点:
1、transform 翻转的方案,需要嵌入很多入侵业务的代码,耦合度较高,复用性较低。如果页面复杂,不建议使用这种方案。

上一篇 下一篇

猜你喜欢

热点阅读