【问题标题】:CSS / JS - calculate angle and spacing for divCSS / JS - 计算 div 的角度和间距
【发布时间】:2021-08-28 05:31:45
【问题描述】:

我正在开发我的网站的移动版本。我将一个元素放置在另一个元素下方(红色下方蓝色)。 这些元素的形状为:clip-path: polygon(0% 0%, 100% 0%, 100% 50%, 100% 62%, 50% 85%, 0% 62%)

他们还得到了一个覆盖,其中有一个文本定位在里面。我的目标是为每个显示分辨率修复右下角的这个文本块。

它在每台设备上的外观:

当我更改视口宽度时它的外观:

首先我写了几个@media (...) 查询来定位文本块。 我注意到我必须为几乎每个设备单独编写查询,因为所需的文本块的顶部间距和角度总是在变化。

所以我尝试计算top 所需的角度和所需的值。我在stackoverflow上找到了一个看起来像这样的方法:

function calculate() {
    const deviceWidth = screen.width;
    const viewportWidth = window.innerWidth;
    const currentRatio = viewportWidth / deviceWidth;
    const angle = currentRatio * ...; // I don't know
    const top = ...; // I don't know

    document.querySelector('.text-container').style.transform = `rotate(${angle}deg)`;
    document.querySelector('.text-container').style.top = `${top}vh`;
}

calculate();
window.addEventListener('resize', calculate);

我很确定,这种方法是一个有用的基础,但我不知道如何继续。

谢谢。

【问题讨论】:

    标签: javascript css sass responsive-design


    【解决方案1】:

    我会以不同的方式使用渐变和蒙版:

    .box {
      padding-top: 200px; /* this will control the overal height */
      overflow:hidden;
      position:relative;
    }
    .box div {
      padding: 10px 0 10px 100%; /* padding-left:100% to push the text to the center */
      color: #fff;
      font-size:25px;
      background: #248a8a;
      transform-origin:bottom;
      transform:rotate(-20deg); /* control the rotation of the text */
      margin:0 -50% 0; /* negative margin to create some overlow and avoid the bad effect of rotation */
    }
    
    .one {
      background:cyan;
    }
    .one::before {
      content:"";
      position:absolute;
      z-index:9;
      pointer-events:none;
      inset:0;
      background: 
        linear-gradient(to bottom right,#0000 49.8%,#dc143c 50%) bottom 0 right calc(50% - 500px),
        linear-gradient(to bottom left ,#0000 49.8%,#dc143c 50%) bottom 0 left  calc(50% - 500px);
      /* keep the 1000px a random but big value 
         adjust 363px based on the angle you will be using
         The formula is tan(20deg) = 363/1000
      */
      background-size:1000px 363px; 
      background-repeat:no-repeat;
    }
    
    .two {
      background:#dc143c;
      -webkit-mask:
        linear-gradient(to bottom right,#000 49.8%,#0000 50%) bottom 0 right calc(50% - 500px),
        linear-gradient(to bottom left ,#000 49.8%,#0000 50%) bottom 0 left  calc(50% - 500px);
      /* same logic as above */
      -webkit-mask-size:1000px 363px;
      -webkit-mask-repeat:no-repeat;
    }
    .two div {
      background:#7c2c3c;
    }
    <div class="box one">
      <div>Text block 1</div>
    </div>
    <div class="box two">
      <div>Text block 1</div>
    </div>

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 2017-10-23
      • 1970-01-01
      • 2015-09-24
      • 2013-09-12
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多