我想創建一個 HTML 串列,該串列將每周自動洗牌一次,任何訪問該網站的人都會查看相同的洗牌串列。改組的 JavaScript 與該問題上投票率最高的問題相同,因此我將避免在此處發布。
問題在于,混洗串列在設備之間不一致。我曾嘗試設定一個計時器來控制腳本何時激活,您可以在此處查看:
var ul = document.querySelector("ul"), // get the list
temp = ul.cloneNode(true); // clone the list
// shuffle the cloned list (better performance)
for (var i = temp.children.length 1; i--; )
temp.appendChild(temp.children[Math.random() * i |0] );
var weekInMilliseconds = 60*1000; // == 604800000 ms
var lastInfo = parseInt(localStorage.getItem('info'), 10); // either NaN or timestamp
if(isNaN(lastInfo))
lastInfo = 0; // 1970, mind you
// if last info showed earlier than one week ago:
if(lastInfo < (Date.now() - weekInMilliseconds)){
localStorage.setItem('info',Date.now()); // set info date now
ul.parentNode.replaceChild(temp, ul); // copy shuffled back to 'ul' // display your information
}
我的問題是,串列再次不一致,雖然它確實成功阻止腳本激活,直到足夠的時間過去,因為沒有對 HTML 的實際更改,如果在間隔之前有重繪 該頁面將按照原始 HTML 中撰寫的默認、未打亂的串列順序加載。
我對網頁設計很陌生,所以我不確定接下來要嘗試什么,而且我對 W3 的瀏覽一直沒有結果。任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
所以隨機洗牌會不一致,因為每次重新加載頁面時它都會有所不同。要始終如一地洗牌,您可以嘗試創建一個偽隨機洗牌邏輯 - 因此請避免Math.random()在此處使用。
解釋
我們需要創建一個種子,在這種情況下,我們正在計算日歷周索引并將這個特定數字與當前年份連接起來,以避免每年重復相同的洗牌行為。
const seed = Math.ceil((new Date().getDay() 1 Math.floor((new Date() - new Date(new Date().getFullYear(), 0, 1)) / (24 * 60 * 60 * 1000))) / 7) new Date().getFullYear();
我們需要一個像這樣簡單的方法的“隨機”生成器:
const getRandom = () => {
const val = seed / (2 ** 32);
seed = (1664525 * seed 1013904223) % (2 ** 32);
return val;
}
現在我們可以使用此問題的鏈接答案開始對串列中的條目進行洗牌:
for (var i = list.children.length; i >= 0; i--)
list.appendChild(list.children[getRandom() * i | 0]);
片段
看看這個作業片段,注意串列的順序每周都會改變:
// create seed that changes every new week and will not repeat since we concat it with the current year
let seed = Math.ceil((new Date().getDay() 1 Math.floor((new Date() - new Date(new Date().getFullYear(), 0, 1)) / (24 * 60 * 60 * 1000))) / 7) new Date().getFullYear();
// create pseudo random numbers
const getRandom = () => {
const val = seed / (2 ** 32);
seed = (1664525 * seed 1013904223) % (2 ** 32);
return val;
}
// pseudo shuffel list
const list = document.querySelector('ol');
for (let i = list.children.length; i >= 0; i--)
list.appendChild(list.children[getRandom() * i | 0]);
<ol>
<li>Al Pacino</li>
<li>Bill Gates</li>
<li>Carsten Stahl</li>
<li>David Beckham</li>
<li>Elon Musk</li>
<li>Frank Ocean</li>
</ol>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447915.html
標籤:javascript html html 列表 洗牌
