Javascript 使用JS在媒体查询中仅重新加载网页一次
我只想在某个媒体查询中重新加载页面一次,但每次加载网页时,都会运行媒体查询并在循环中重新加载页面 我试图使用以下问题的答案,但没有帮助,这个问题仍然存在。 我的密码Javascript 使用JS在媒体查询中仅重新加载网页一次,javascript,html,jquery,node.js,Javascript,Html,Jquery,Node.js,我只想在某个媒体查询中重新加载页面一次,但每次加载网页时,都会运行媒体查询并在循环中重新加载页面 我试图使用以下问题的答案,但没有帮助,这个问题仍然存在。 我的密码 tablet(); function tablet(){ const mql = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)'); checkMedia(mql); mql.addListener(check
tablet();
function tablet(){
const mql = window.matchMedia('screen and (min-width: 576px) and (max-width: 991px)');
checkMedia(mql);
mql.addListener(checkMedia);
function checkMedia(mql){
if(mql.matches){
console.log('tablet');
// location.reload();
location.href = window.location.href + "?tablet=1";}}}
您可以使用
localStorage
解决您的问题
在重新加载页面之前,可以在localStorage
中存储一个值。每次重新加载页面时,只需检查localStorage
中是否存在该变量:
function checkMedia(mql){
// Check here if there is a value exists in the localStorage
if(mql.matches && !localStorage.getItem("your_variable")){
console.log('tablet');
// location.reload();
// Before reload, store a variable in localStorage
localStorage.setItem("your_variable", true);
location.href = window.location.href + "?tablet=1";}}}