javascript - 如何使用 Javascript 逐渐更改属性值?例如。缓入缓出

标签 javascript html css

我想将元素的属性(SVG 的过滤器)从 0 更改为 10,然后无限地更改回 0。为此,我制作了一个 js 函数:

let flag = 0;
let loader = setInterval(breathe, 1000);

function breathe() {
  if (flag === 0) {
    document
      .getElementById("main-blur")
      .setAttribute("stdDeviation", "10");
    flag = 1;
    return;
  } else {
    document
      .getElementById("main-blur")
      .setAttribute("stdDeviation", "0");
    flag = 0;
    return;
  }
}

问题是模糊值直接从10变成了0。我希望它逐渐增加和减少呼吸类型的效果。

最佳答案

如果您打算使用 JS 解决方案而不是使用 <animate> , 你应该使用 window.requestAnimationFrame() :

// Get a reference to the SVG filter only once:
const gaussianBlur =  document.getElementById('gaussianBlur');

// To control the animation: 0 to 100 we increase blur, 100 to 200 we decrease blur. We use these
// values instead of 0-10 and then divide by 10 to produce a smoother animation.
let step = 0;

function tick() {
  const blur = step < 100 ? step : 200 - step;

  // Update blur (converting step to 0-10). You could change this to take into account time:
  gaussianBlur.setAttribute('stdDeviation', blur / 10);

  // Update step:
  step = (step + 1) % 200;
  
  requestAnimationFrame(tick);
}

tick();
#element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
}
<svg id="element" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <filter id="blurFilter" x="-100%" y="-100%" width="300%" height="300%">
    <feGaussianBlur id="gaussianBlur" />
  </filter>
  
  <circle cx="50" cy="50" r="25" style="filter: url(#blurFilter); " />
</svg>

否则,使用 <animate> , 你需要使用它的 values keyTimes 属性:

#element {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 200px;
  height: 200px;
  transform: translate(-50%, -50%);
}
<svg id="element" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <filter id="blurFilter" x="-100%" y="-100%" width="300%" height="300%">
    <feGaussianBlur id="gaussianBlur" stdDeviation="1" />
  </filter>
  
  <animate
    xlink:href="#gaussianBlur"
    attributeName="stdDeviation"
    dur="2s"
    repeatCount="indefinite"
    values="0; 10; 0"
    keyTimes="0; .5; 1"
  />
  
  <circle cx="50" cy="50" r="25" style="filter: url(#blurFilter); " />
</svg>

关于javascript - 如何使用 Javascript 逐渐更改属性值?例如。缓入缓出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59669397/

相关文章:

javascript - 错误 TS2345 : Argument of type 'Event' is not assignable to parameter of type '{ target: { value: string; }; }'

javascript - lodash,获取匹配元素的索引?

javascript - 为什么 AJAX 的返回值几乎立即消失了?

php - 限制桌面上网页的大小调整和缩放

javascript - 如何提前获取元素属性(不是在我调用函数时)

javascript - Sinon 监视未注册的 console.log 调用

android - 所有 W3C 规范和不同浏览器的实现的困惑

html - IE7 并在 MS CRM 的 iframe 中发布表单 = 新窗口

javascript - 使用 javascript 设置变量并通过表单提交

asp.net ajax 控制工具包组合框在字段集中显示位置样式为 :relative 时显示不正确