有没有办法循环使用仅使用JS将文章应用于随机单词的文本?
我想创建与此类似的内容(http://codepen.io/BrianDGLS/pen/wBgXwo),但不必使用id定义多个span标记。
var ids = ["a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u"];
function shuffle(array) {
var item = array[Math.floor(Math.random() * array.length)];
var remove = array[Math.floor(Math.random() * array.length)];
document.getElementById(item).className = "shine";
document.getElementById(remove).className = "";
setTimeout(function () {
shuffle(ids);
}, 1000);
}
window.onload = shuffle(ids);
答案 0 :(得分:1)
由于HTML的工作方式,您无法在textnode上放置类。您只能在可能包含或不包含文本节点的元素上放置一个类。
你可以做的是在JavaScript中剪切文本,这样你就不需要手动添加跨度。
这是一个实例:http://codepen.io/anon/pen/YPNvZy动画行为有点奇怪。我不确定是什么原因引起的,但它确实演示了如何自动拆分文本。
我也选择将结构保持为一首诗,我不确定你是否想要这样。
var poem = "I will arise and go now,\n"
+ "and go to Innisfree,\n"
+ "And a small cabin build there,\n"
+ "of clay and wattles made;\n"
+ "Nine bean-rows will I have there,\n"
+ "a hive for the honey-bee,\n"
+ "And live alone in the bee-loud glade.\n"
+ "And I shall have some peace there,\n"
+ "for peace comes dropping slow,\n"
+ "Dropping from the veils of the morning\n"
+ "to where the cricket sings;\n"
+ "There midnight’s all a glimmer,\n"
+ "and noon a purple glow,\n"
+ "And evening full of the linnet’s wings.\n"
+ "I will arise and go now,\n"
+ "for always night and day\n"
+ "I hear lake water lapping\n"
+ "with low sounds by the shore;\n"
+ "While I stand on the roadway,\n"
+ "or on the pavements grey,\n"
+ "I hear it in the deep heart’s core.";
var lines, i, div, divs = [];
lines = poem.split("\n");
for (i = 0; i < lines.length; i += 1) {
div = document.createElement("div");
div.className = "line";
div.appendChild(document.createTextNode(lines[i]));
divs.push(div);
document.getElementById("container").appendChild(div);
}
function shuffle(divs) {
var item = divs[Math.floor(Math.random() * divs.length)];
var remove = divs[Math.floor(Math.random() * divs.length)];
item.className = "shine";
remove.className = "";
}
setInterval(function () {
shuffle(divs);
}, 1000);
答案 1 :(得分:0)
为了添加样式,单词必须在单个元素中。
但是,您不一定需要使用数组通过ID查找它们,因为它们已经有效地存在于DOM中的数组中,您可以使用node.childNodes []进行访问。