字母的抖动效果



jQuery(function ($) {
var target = $("#target");
target.html(target.text().replace(/./g, "<span>$&</span>"));
setTimeout(runAnimation, 250);
function runAnimation() {
var index, spans;
index = 0;
spans = target.children();
doOne();
function doOne() {
var span = $(spans[index]);
if (!$.trim(span.text())) {
// Skip blanks
next();
return;
}
// Do this one
span.css({
position: "relative",
})
.animate(
{
top: "-20",
},
"fast"
)
.animate(
{
top: "0",
},
"fast",
function () {
span.css("position", "");
next();
}
);
}
function next() {
++index;
if (index < spans.length) {
doOne();
} else {
setTimeout(runAnimation, 500);
}
}
}
});
.title {
margin: auto;
width: 50%;
color: black;
text-align: right;

}
#target:hover {
color: rgb(21, 121, 252);
animation-name: bounce;
animation-duration: 2s;
}

@keyframes bounce {
0%   { transform: translateY(0); }
50%  { transform: translateY(-50px); }
100% { transform: translateY(0); }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="title">
<p style="font-size: 45px;"><span id="target">I</span><span id="target">'</span><span id="target">m</span><span>
</span><span id="target">K</span><span id="target">r</span><span id="target">i</span><span id="target">s</span>
</p>
</div>

我试图在每个字母上添加摆动效果,但我不能让它工作,我希望字母在悬停时变得更大一些,并使效果运行。我只是在学习javascript,所以我不是很擅长它,片段不能工作,我不知道它的问题是什么。我发现这个代码的抖动效果,但它不工作,有人能帮助吗?由于

与其手动输入单个span块中的字母,不如让JavaScript来完成。这将更加灵活。

除此之外,你不需要为动画使用JavaScript,而是使用CSS。这样会简单得多,也容易处理。

const animatedElements = document.getElementsByClassName('animate');
[...animatedElements].forEach(elm => {
let text = elm.innerText.split(''); // Split the text into letters and store them in an array

elm.innerText = ''; // Clear the text in the div

// Add the letters one by one, this time inside a <span>
text.forEach(letter => {
const span = document.createElement('span');
span.innerText = letter;
elm.appendChild(span);
})
})
.animate>span {
display: inline-block; /* Changing display from the default `inline` to `inline-block` so that `transform` rules apply */
white-space: break-spaces; /* This is necessary so that the `inline-block` does not collapse the "spaces" */
transition: transform 200ms ease-in-out;
}
.animate>span:hover {
transform: translateY(-10px);
}

/* The following rules are just to format the embedded result */
.animate {
margin: 40px;
font-size: 40px;
}
<div class="animate">
I'm Kris
</div>

最新更新