gpt4 book ai didi

javascript 将元素附加到 div 中

转载 作者:行者123 更新时间:2023-11-28 10:44:59 25 4
gpt4 key购买 nike

我用动态单词构建了这个循环动画,但我需要将所有跨度附加到 div <div id"wordcloud"></div> 中。我无法按照自己的意愿完成任务,因此我需要一些帮助。

var interval = 100;
var width = 800;
var height = 500;

var words = [
'Liberty',
'Morality',
'Modesty',
'Curiosity',
'Imagination',
'Excitement',
'Structure',
'Intellect',
'Friendliness',
'Conversation'
];
var wordPlacementInterval = setInterval(function() {
var currentWord = words.shift();
if (currentWord) {


var word = document.createElement('span');

word.innerHTML = currentWord;
word.style.top = Math.floor((Math.random() * height) + 1) + 'px';
word.style.left = Math.floor((Math.random() * width) + 1) + 'px';
document.body.appendChild(word);
} else {
clearInterval(wordPlacementInterval);
}
}, interval);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wordcloud"></div>

最佳答案

您丢失了 =在 id 属性 <div id[HERE]"wordcloud"></div>

然后将您创建的元素添加到

document.querySelector('#wordcloud').appendChild(word);

像这样:

var interval = 100;
var width = 800;
var height = 500;

var words = [
'Liberty',
'Morality',
'Modesty',
'Curiosity',
'Imagination',
'Excitement',
'Structure',
'Intellect',
'Friendliness',
'Conversation'
];
var wordPlacementInterval = setInterval(function() {
var currentWord = words.shift();
if (currentWord) {


var word = document.createElement('span');

word.innerHTML = currentWord;
word.style.top = Math.floor((Math.random() * height) + 1) + 'px';
word.style.left = Math.floor((Math.random() * width) + 1) + 'px';
document.querySelector('#wordcloud').appendChild(word);
} else {
clearInterval(wordPlacementInterval);
}
}, interval);
<div id="wordcloud"></div>

如果您尝试使用通过 javascript 设置的位置,您需要添加一些 CSS,例如:

var interval = 100;
var width = 800;
var height = 500;

var words = [
'Liberty',
'Morality',
'Modesty',
'Curiosity',
'Imagination',
'Excitement',
'Structure',
'Intellect',
'Friendliness',
'Conversation'
];
var wordPlacementInterval = setInterval(function() {
var currentWord = words.shift();
if (currentWord) {


var word = document.createElement('span');

word.innerHTML = currentWord;
word.style.top = Math.floor((Math.random() * height) + 1) + 'px';
word.style.left = Math.floor((Math.random() * width) + 1) + 'px';
document.querySelector('#wordcloud').appendChild(word);
} else {
clearInterval(wordPlacementInterval);
}
}, interval);
#wordcloud {
position: relative;
}

#wordcloud span {
position: absolute;
}
<div id="wordcloud"></div>

关于javascript 将元素附加到 div 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com