<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>容量</title> </head> <body> <div class="use"> 使用: </div> <button class="btn1">获取使用</button> <hr /> <div class="total"> 总数: </div> <button class="btn2">获取总数</button> <button class="btn3">暂停总数</button> <hr /> <script> function getUseSize() { var size = 0; for(item in window.localStorage) { if(window.localStorage.hasOwnProperty(item)) { size += window.localStorage.getItem(item).length; } } document.querySelector('.use').innerHTML = '使用:' + (size / 1024).toFixed(2) + 'KB' } document.querySelector('.btn1').addEventListener('click', function () { getUseSize(); }) var timer function getTotalSize() { localStorage.clear(); var test = '0123456789'; var add = function(num) { num += num; if(num.length === 10240) { test = num; return; } add(num); } add(test); var sum = test; timer = setInterval(function(){ sum += test; try { localStorage.removeItem('test'); localStorage.setItem('test', sum); document.querySelector('.total').innerHTML = '总数:' + sum.length / 1024 + 'KB' } catch(e) { alert(sum.length / 1024 + 'KB超出最大限制'); clearInterval(timer); } }, 0.1) } document.querySelector('.btn2').addEventListener('click', function () { getTotalSize(); }) document.querySelector('.btn3').addEventListener('click', function () { clearInterval(timer); }) </script> </body> </html>