javascript - 悬停文本,临时更改一些字母
问题描述
这是我的代码:
$("#hole").mouseover(function() {
$("#text").text("At random, some letters from the previous text should be replaced with this emoji: ");
});
* {
font-size: 40px;
cursor: crosshair;
}
html,
body {
height: 100%;
width: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
#text {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#hand {
position: fixed;
transform: scale(0);
pointer-events: none;
transition: transform 1.2s linear;
}
#hole:hover~#hand {
position: fixed;
transform: scale(20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
<div id="hole">️</div>
<div id="hand"></div>
如果您将鼠标悬停在孔表情符号上,文本中的一些字母应随机临时替换为.
最简单的方法是什么?开始有意义.text("...")
吗?然后应该有一个随机功能集成?
解决方案
您可以获得要更改为ok
符号的元素的文本。然后split
是每个字符的字符串。定义一个空数组来保存带有已更改字符的新数组为okay
符号。然后使用 遍历el.split()
数组$.each()
。
我使用辅助函数使用条件重新分配具有值的新数组。检查数组中的值是否等于随机选择的值,如果是,我们okay
在使用辅助函数映射值时将其值更改为新数组中的符号。
最后,我们加入数组以创建要放置在元素文本中的字符串。
let assign = (array, index, newValue) => {
array[index] = newValue;
return array;
}
$("#hole").mouseover(() => {
const arr = $("#text").text().split(' ')
const random = arr[~~(Math.random() * arr.length)]
const changed = [];
$.each(arr, (i,val) => {
val === random ?
assign(changed, i, ''):
assign(changed, i, val)
})
$("#text").text(changed.join(" "))
});
* {
font-size: 40px;
cursor: crosshair;
}
html,
body {
height: 100%;
width: 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
#text {
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#hand {
position: fixed;
transform: scale(0);
pointer-events: none;
transition: transform 1.2s linear;
}
#hole:hover~#hand {
position: fixed;
transform: scale(20);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
<div id="hole">️</div>
<div id="hand"></div>
推荐阅读
- mongodb - 如何在 Windows 上设置 MongoDB 日志轮换?
- java - 尝试调用虚拟方法 'void androidx.recyclerview.widget.RecyclerView.setAdapter
- c++ - 不同的输出取决于我是否打印返回值
- r - 如何在闪亮服务器的反应函数中添加多个输入变量?
- python - 从 index.ts 触发导出可执行脚本命令
- pandas - 在熊猫中单独计算时间增量
- f# - 如何通过在 F# 中为每个惰性对象创建值来转换其中包含惰性对象的异构数组(无反射)
- spring - 创建自己的配置类
- javascript - 访问 javascript 返回函数的属性时遇到问题
- php - 将默认值设置为输入类型日期 - Laravel