首页 > 解决方案 > 悬停文本,临时更改一些字母

问题描述

这是我的代码:

$("#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">️&lt;/div>
<div id="hand"></div>

如果您将鼠标悬停在孔表情符号上,文本中的一些字母应随机临时替换为.

最简单的方法是什么?开始有意义.text("...")吗?然后应该有一个随机功能集成?

标签: javascriptjquery

解决方案


您可以获得要更改为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">️&lt;/div>
<div id="hand"></div>


推荐阅读