gpt4 book ai didi

javascript - 如何预测 HTML 元素的宽度以便在不透明度和宽度上进行 CSS 转换?

转载 作者:行者123 更新时间:2023-11-30 14:05:41 25 4
gpt4 key购买 nike

  • 我正在处理一个带有 innerTextspan 节点。
  • 在运行时,我将更改 innerText,因此节点的 offsetWidth 会发生变化,具体取决于 future 的 innerText 长度。
  • 我需要预见 future -offsetWidth,以便通过 CSS 处理宽度本身的transition
  • 在这种情况下,特别是,我需要在 opacitywidth both 上做一个transition > span 元素,所以我无法立即更改 inneText

如何预测 width 的准确值?

更一般地说,有一种方法可以“模拟”DOM 更改以了解future-CSS-properties

可能的起始代码片段

let h1 = document.getElementsByTagName("h1")[0];
let span = document.getElementsByTagName("span")[0];
h1.addEventListener("click", function() {
if(span.innerText == "Better") {
span.innerText = "Awsome";
} else {
span.innerText = "Better";
}
})
h1 span {
border: 1px solid red;
display: inline-block;
padding: 4px;
transition-property: all;
}
<h1>Hello <span>Awsome</span> World!</h1>

最佳答案

正如我在评论中提到的,您可以克隆该元素,将其内容设置为您想要的内容,并测量其宽度。然后,您可以将原始宽度更改为从克隆元素获得的宽度。

像这样:

let h1 = document.getElementsByTagName("h1")[0];
let span = document.getElementsByTagName("span")[0];
span.style.width = `${span.clientWidth}px`;
h1.addEventListener("click", function() {
const nextWord = getNextWord();
const featureWidth = getFeatureWidth(nextWord);
span.style.color = 'rgba(0, 0, 0, 0)';
span.style.width = `${featureWidth}px`;
setTimeout(() => {
span.textContent = nextWord;
span.style.color = 'rgba(0, 0, 0, 1)';
}, 300);
});

function getNextWord() {
if(span.innerText == "Better") {
return "Awsome";
}
return "Better";
}

function getFeatureWidth(word) {
const clonedSpan = document.createElement('span');
clonedSpan.setAttribute('style', 'position: absolute;z-index: -1');
clonedSpan.textContent = word;
h1.appendChild(clonedSpan);
const width = clonedSpan.clientWidth;
h1.removeChild(clonedSpan);
return width;
}
h1 span {
border: 1px solid red;
display: inline-block;
padding: 4px;
transition: all .3s ease;
}
<h1>Hello <span>Awsome</span> World!</h1>

关于javascript - 如何预测 HTML 元素的宽度以便在不透明度和宽度上进行 CSS 转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55442162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com