首页 > 解决方案 > mouseenter 后的段落随机大写单词

问题描述

我有 3 段。在标签上使用鼠标悬停事件后,我需要 JS 代码使这个虚拟文本中的随机单词变为大写 P。它会在我悬停的每个段落上每 3 秒随机更改一次。

HTML:

<head>
    <style>
     p {
         margin-top: 50px;
         font-size: 24px;
     }
    </style>
</head>
<body>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p>
  <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old</p>
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</body>

标签: javascripthtmlsettimeoutuppercasemouseenter

解决方案


[...document.getElementsByTagName('p')].forEach(elem => {
  let oldText = elem.innerHTML;
  elem.onmouseenter = () => {
    elem.onmouseenter = '';
    setInterval(() => elem.innerHTML = oldText.split('').map(word => Math.random() > 0.15 ? word.toLowerCase() : word.toUpperCase()).join(''), 3000);
  }
})
<head>
  <style>
    p {
      margin-top: 50px;
      font-size: 24px;
    }
  </style>
</head>

<body>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p>
  <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old</p>
  <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</body>


推荐阅读