单击特定的字母后,如何获得原始条件



这是代码:

$(document).ready(function() {
$('div').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
$('div').click(function() {
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
});
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 9vw;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Stack Overflow</div>

如果你点击单词,所有字母都应该得到一个随机的位置。现在:如果你点击任何一个字母,它应该看起来像以前一样。所以它应该像切换函数一样工作。

添加一个标志来检查是否需要随机字符,然后将位置重置为相对、左&top为0。

$(document).ready(function() {
var isRandom = false;
$('div').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
$('div').click(function() {
isRandom = !isRandom;
if(isRandom) {
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
} else {
$('span').each(function() {
$(this).css({
"position": "relative"
});
$(this).animate({
left: 0,
top: 0,
});
});
}

});
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 9vw;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Stack Overflow</div>

您只需要删除使用$(this).find("span").css({ "left": "",..})添加到span的css,并添加一些类来标识文本的当前状态。

演示代码

$(document).ready(function() {
$('div').html(function(i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
$('div').click(function() {
if ($(this).hasClass("already")) {
//remove css added to span
$(this).find("span").css({
"left": "",
"top": "",
"position": ""
});
//remove already class
$(this).removeClass("already")
} else {
//add class to identify 
$(this).addClass("already")
$('span').each(function() {
$(this).css({
"position": "absolute"
});
$(this).animate({
left: Math.random() * window.outerWidth / 2,
top: Math.random() * window.outerHeight / 2,
});
});
}
});
});
html,
body {
width: 100%;
height: 100%;
}
div {
font-family: Arial;
font-size: 9vw;
text-transform: uppercase;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Stack Overflow</div>

最新更新