如何在每次新访问页面时打乱div顺序?
问题需求
我写的代码现在能在页面刷新时打乱div的顺序,但我想要改成每次新访问页面时就执行打乱操作。我不太懂jQuery/JavaScript,想请人帮忙修改。
原代码
JavaScript
onload = function() { var parent = document.getElementById("shuffle"); var frag = document.createDocumentFragment(); while (parent.children.length) { frag.appendChild(parent.children[Math.floor(Math.random() * parent.children.length)]); } parent.appendChild(frag); } $(document).ready(function() { window.location.href = window.location.href; });
CSS
#shuffle>div { float: left; line-height: 30px; width: 30px; text-align: center; background-color: steelblue; color: #fff; border-radius: 4px; margin: 3px; } #shuffle { max-width: 360px; }
HTML
<div id="shuffle"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>16</div> <div>17</div> <div>18</div> <div>19</div> <div>20</div> </div>
解决方法
你原来的代码里,$(document).ready里写的强制刷新页面的逻辑完全没必要,反而会导致页面重复加载,才出现只有刷新时才打乱的情况。只需要保留onload里的打乱逻辑,删掉重复刷新的代码就行——这样每次新打开页面,加载完成后就会自动执行一次打乱,不会额外刷新页面。
修改后的JavaScript代码:
window.onload = function() { var parent = document.getElementById("shuffle"); var frag = document.createDocumentFragment(); while (parent.children.length) { frag.appendChild(parent.children[Math.floor(Math.random() * parent.children.length)]); } parent.appendChild(frag); }
要是想用jQuery写法,也可以改成这样:
$(document).ready(function() { var parent = $("#shuffle"); var children = parent.children().sort(function() { return Math.random() - 0.5; }); parent.empty().append(children); });
这两种写法都能实现每次新访问页面时自动打乱div顺序的需求,不用再强制刷新页面。
内容的提问来源于stack exchange,提问作者Diana
相关产品推荐
相关产品推荐

