如何一次显示一个段落的一个新单词,通过按键或鼠标点击移动

How do I display a single new word of a paragraph at a time, moving by keypress or mouseclick?

本文关键字:一个 鼠标 移动 新单词 显示 何一次 段落      更新时间:2023-09-26

假设我有这样的东西:

<p>Here are several words in a sentence.</p>

我想弄清楚如何通过按键或鼠标点击一个接一个地显示每个单词,直到它到达最后。

例如:


(点击这里)这里有(点击)
这里有几个,等等。

这可能是基本的,但我不是很好,我喜欢一些帮助!

谢谢!

我只是想对@Dean做一些干预。复制答案并制作代码,以便将其粘贴到您的项目中,并实现此功能:

你的html应该是这样的:

<div id="adiv"></div>

你应该添加以下javascript代码:

var index, newsentence, sentence, words;
sentence = "Here are several words in a sentence";
words = sentence.split(" ");
index = 0;
newsentence = "";
$(document).click(function(e) {
  if (e.button === 0 && index < words.length) {
    newsentence += words[index];
    newsentence += " ";
    $("#adiv").html(newsentence);
    index = index + 1;
  }
});

如果你对代码有任何疑问就问!

这已经变成了一个jQuery插件:word-reveal.

虽然其他两个答案可以工作(某种程度上),但它们不是很可重用。当你有一个以上的容器,你想揭示多于一个句子,会发生什么?我创建了一个jQuery插件,可以很容易地在整个页面中重用。

设置

    包含jQuery
  • 从GitHub下载插件,并将其包含在
  • 页面
  • 你已经准备好了!

HTML

为每个divp标签设置一个id。多用途示例:

<p id="firstRevealer"></p>
<p id="secondRevealer"></p>
<p id="thirdRevealer"></p> 

jQuery

$(document).ready(function() {
    $("#firstRevealer").wordReveal({text:"This reveals one word at a time."});
    $("#secondRevealer").wordReveal({text:"Adding more text is easy!"});
    $("#thirdRevealer").wordReveal({text:"It <b>also</b> works on <em>some</em> tags, since it splits on <b>spaces</b>!"});
});
CSS

我在示例中添加了CSS,以明确您单击的地方显示下一个单词。一个不同的答案注册了document上的点击,但是任何点击(例如,对于可展开的菜单)都会添加一个单词。

p { 
    padding: 10px; 
    margin:10px; 
    min-height:25px; 
    background-color:#BADA55 
}

小提琴。

注意

可以很容易地扩展到作用于其他事件(按键)。

<script type="text/javascript">
var sentence = "Here are several words in a sentence";
var words = sentence.split(" ");
var index = 0;
var newsentence = "";
function clickit() {
  newsentence += sentence[index];
  index = index + 1;
}