刷新后在div中随机显示内容 [英] Randomly display content in a div after refresh
问题描述
我希望有一个在刷新后随机显示内容的div.我找到了可以正常工作的代码,但不能100%正常工作,因此我试图在此处查找错误.
I want to have a div that randomly displays content after refresh. I found a code that kind of worked, but it doesn't 100% work, so I'm trying to find the error here.
I was asked to post this as a new topic after using the code of [this] (randomly display a div class using JQuery) question, but it did not work properly.
标题中的代码
window.onload=function() {
var E = document.getElementsByClassName("item");
var m = E.length;
var n = parseInt(Math.random()*m);
for (var i=m-1;i>=0;i--) {
var e = E[i];
e.style.display='none';
}
E[n].style.display='';
}
我体内有以下
<div class="item">Lorem ipsum dolor</div>
<div class="item">Lorem ipsum dolor sit amet</div>
<div class="item">Lorem ipsum </div>
<div class="item">Lorem </div>
在加载页面时,它将显示所有item-divs
,然后在加载其余部分(div位于最顶部)后,除一个以外的所有内容都将被隐藏.
When loading the page it displays all of the item-divs
and then after the rest is loaded (the divs are at the very top) all except for one are hidden.
为什么会这样?如何更改代码,以便根本不显示其他内容?
Why is this happening? how does the code need to be changed so the other contents aren't displayed at all?
推荐答案
代码不起作用的原因是因为页面加载时所有item
div都可见.您需要使用display: none;
The reason your code doesn't work is because all your item
div's are visible when the page loads. you need to hide them in the .item
css using display: none;
由于您还标记了JQuery,因此可以像这样更新JS
since you've tagged JQuery as well, you can update your JS like this
$(function(){
var random = Math.floor(Math.random() * $('.item').length);
$('.item').eq(random).show();
});
我已经建立了一个可以正常工作的 JSFIDDLE ,其中包含一些
I've put up a working JSFIDDLE with some styling
. Hope this helps
这篇关于刷新后在div中随机显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!