我正在嘗試制作一個網站,將滑鼠懸停在由兩個字母換位組成的拼寫錯誤上可以糾正它,如下所示:
var swap = document.querySelector('.swap');
swap.addEventListener('mouseover', swapIn);
swap.addEventListener('mouseout', swapOut);
function swapIn(e) {
e.target.parentNode.firstChild.classList.toggle('shifted-right');
e.target.parentNode.lastChild.classList.toggle('shifted-left');
}
function swapOut(e) {
e.target.parentNode.firstChild.classList.toggle('shifted-right');
e.target.parentNode.lastChild.classList.toggle('shifted-left');
}
body {
font-size: 24px;
}
.swap {
display: inline;
}
span {
-webkit-transition: all 0.3s linear;
-moz-transition: all 0.3s linear;
-o-transition: all 0.3s linear;
transition: all 0.3s linear;
}
.shifted-right {
margin-left: 20px;
color: blue;
}
.shifted-left {
margin-left: -25px;
color: red;
}
E<div class="swap" id="swap"><span class="left-swap" id="ls">q</span><span class="right-swap" id="rs">c</span></div>uis me vivit fortunatior?
但是,如您所見,字母不能很好地交換,此外,我不想計算每個不同字母寬度的精確邊距。
有什么更好的方法來做到這一點?
uj5u.com熱心網友回復:
offsetLeft可以通過使用屬性計算它們與其父級的相對位置來切換同一個單詞中的兩個字母。
將值彼此相減并使用Math.abs保持整數為正數。這個數字distance在兩個字母之間。一個字母必須向左移動整個距離,而另一個字母必須向右移動相同的距離才能切換位置。使用距離設定一個 CSS 變數,以便我們可以將計算傳遞給 CSS。
在 CSS 中,我們可以使用:hover偽選擇器設定懸停樣式,并使用 CSS 變數進行適當的過渡。而不是將滑鼠懸停在一個字母上,而是將滑鼠懸停在整個單詞上。
代替margin,使用transform; 此屬性不會弄亂布局,只會對目標元素進行任何操作。
const word = document.querySelector('.word');
const [e, a] = word.querySelectorAll('.letter');
const distance = Math.abs(e.offsetLeft - a.offsetLeft);
word.style.setProperty('--distance', `${distance}px`);
.word {
display: inline-block;
padding: 15px;
position: relative;
font-size: 32px;
background-color: #f7f7f7;
border: 1px dashed #d0d0d0;
border-radius: 3px;
cursor: help;
}
.word .letter {
display: inline-block;
color: red;
transition: color 500ms ease-in-out, transform 500ms ease-in-out;
}
.word:hover .letter {
color: green;
}
.word:hover .letter:first-of-type {
transform: translate(var(--distance), 0);
}
.word:hover .letter:last-of-type {
transform: translate(calc(var(--distance) * -1), 0);
}
<span class="word">
App<span class="letter">e</span>r<span class="letter">a</span>nt
</span>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422066.html
標籤:
