文字输入特效少量JS代码实现,var在css中使用,setProperty在js中的使用

实现效果

在这里插入图片描述

代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>输入文字特效</title>
</head>
<style>
  :root {
    font-size: 20px;
  }

  body {
    display: flex;
    min-height: 100vh;
    justify-content: center;
    align-items: center;
    margin: 0;
    padding: 0;
  }

  h1 {
    font-size: 6rem;
    margin: 0;
    padding: 0;
    font-family: monospace;
    position: relative;
  }

  h1::after {
    content: '';
    display: inline-block;
    position: absolute;
    width: 20px;
    height: 6rem;
    background: #000;
    border-radius: 2px;
    right: -30px;
  }

  h1 span {
    --deday: 10s;
    display: inline-block;
    overflow: hidden;
    width: 0ch;
    animation: 0.1s text-in ease-in-out forwards;
    animation-delay: var(--delay);
  }

  h1.ended::after {
    animation: 1.1s typeing steps(2, jump-none) infinite;
  }

  @keyframes text-in {
    from {
      width: 0ch;
    }

    to {
      width: 1ch;
    }
  }

  @keyframes typeing {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }
</style>

<body>
  <h1>cssStudy</h1>
  <script>
    const h1 = document.querySelector('h1')
    // 给文字添加span标签
    h1.innerHTML = h1.textContent.replace(/\S/g, '<span>$&</span>')
    let delay = 0
    // 给动画添加延时
    document.querySelectorAll('span').forEach((span, index) => {
      delay += 0.1
      if (index === 3) {
        delay += 0.3
      }
      // https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleDeclaration/setProperty
      span.style.setProperty('--delay', `${delay}s`)
    });
    // https://www.runoob.com/jsref/event-animationend.html
    h1.addEventListener('animationend', (e) => {
      if (e.target === document.querySelector('h1 span:last-child')) {
        h1.classList.add('ended')
      }
    })
  </script>
</body>

</html>

var 在css中使用

var()函数可以代替元素中任何属性中的值的任何部分。var()函数不能作为属性名、选择器或者其他除了属性值之外的值。(这样做通常会产生无效的语法或者一个没有关联到变量的值。)

例子:

:root {
  --main-bg-color: pink;
}

body {
  background-color: var(--main-bg-color);
}

配合上setProperty()接口简单修改css的变量

CSSStyleDeclaration.setProperty() 方法接口为一个声明了CSS样式的对象设置一个新的值 。

语法

style.setProperty(propertyName, value, priority);

参数

propertyName 是一个 DOMString ,代表被更改的CSS属性。
value可选 是一个 DOMString ,含有新的属性值。如果没有指定, 则当作空字符串。
注意: value 不能包含 “!important” --那个应该使用 priority 参数.
priority可选 是一个 DOMString 允许设置 “important” CSS 优先级。如果没有指定, 则当作空字符串。

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值