4

在过渡期间,有没有办法查看正在过渡的样式规则的目标值是多少? window.getComputedStyle获取插值,并且element.style只查看样式属性(我认为)。

这是问题的演示;我想检索1200px过渡期间的目标高度值:

https://jsfiddle.net/EoghanM/xz5s3ua6/5/

setInterval(function() {
  document.body.children[0].innerHTML = getComputedStyle(document.body.children[0])['height']
}, 300)

setTimeout(function() {
  document.body.children[0].classList.toggle('changing')
}, 1000)
div {
  height: 400px;
  border: 1px solid red;
  width: 200px;
  transition: height 100s linear;
}

div.changing {
  height: 1200px;
}
<div></div>

4

2 回答 2

1

我 99% 确定所有请求元素高度的 DOM 属性和方法(clientHeight、offsetHeight、getBoundingClientRect 等)只会给你内插值。另一种解决方案可能是使用CSSOM从 CSS stylehseet 本身读取值。

在下面的代码中,我们搜索文档的样式表,检查选择器是否存在于规则声明中,如果存在,则返回我们要查找的属性的值。您可以console.log()在下面的样式表和规则的各个部分查看浏览器如何将信息存储为对象。

当然这是一个基于简单测试用例的简单示例。可能有多个规则使用相同的选择器,但这只会找到第一次出现。该解决方案需要更强大才能找到您正在寻找的确切规则。

function getCssRuleValue(selector, property) {
  const styleSheets = document.styleSheets;

  let styleSheetsLen = styleSheets.length;

  while (styleSheetsLen--) {
    const styleSheet = styleSheets[styleSheetsLen];
    const rules = styleSheet.rules;
    
    let rulesLen = rules.length;
    
    while (rulesLen--) {
      const rule = rules[rulesLen];

      // The passed-in selector text is found in the rule text
      if (rule.cssText.indexOf(selector) > -1) {
        return rule.style[property];
      }
    }
  }

  // The selector/property was not found in any document stylesheets
  return -1;
}

setInterval(function() {
  document.body.children[0].innerHTML = 
    getComputedStyle(document.body.children[0])['height']
    + '<br>' +
    getCssRuleValue('.changing', 'height')
}, 300)

setTimeout(function() {
  document.body.children[0].classList.toggle('changing')
}, 1000)
div {
  height: 400px;
  border: 1px solid red;
  width: 200px;
  transition: height 100s linear;
}

div.changing {
  height: 1200px;
}
<div></div>

于 2019-11-14T19:22:58.163 回答
1

getComputedStyle在类的新实例上使用怎么样changing

您可以使用类创建一个 div,changing然后用于getComputedStyle获取类属性(考虑到changing类的高度将是 div 转换后的最终高度),如下所示:

<div class="changing" id="new-changing-div"></div>

并获得它的属性:

const element = document.querySelector('#new-changing-div');
const heightAttribute = window.getComputedStyle(element).getPropertyValue('height');
于 2019-11-14T18:50:26.167 回答