javascript - window.location.replace不断重新加载页面,如何停止?

标签 javascript jquery

我正在创建一个脚本,该脚本会在某些断点处更改 CSS,并在两个确切的点处重定向到另一个页面。

更改 CSS 工作顺利,但重定向点、脚本不断重新加载页面,如何停止它并将其设置为仅重新加载一次并在需要时再次重新加载“分辨率再次更改。”

这是代码:

/*Change CSS in response to common resolutions.*/
$(document).ready(function() {
    checkWidth ();
    $(window).resize(checkWidth);
});

function checkWidth(){
    var windowWidth = $(window).width(),
        cssLocation = $('link[href$="main.css"]');

    if (windowWidth <= 240){
        cssLocation.attr('href','stylesheets/240-main.css');
        }
    else if (windowWidth <= 480){
        /*Redirecting point 1*/
        window.location.replace("smartPhone-index.html");
        cssLocation.attr('href','stylesheets/480-main.css');
        }       
    else if (windowWidth <= 768){
        /*Redirecting point 2*/
        window.location.replace("index.html");
        cssLocation.attr('href','stylesheets/768-main.css');
        }       
    else if (windowWidth <= 1024){
        cssLocation.attr('href','stylesheets/1024-main.css');
        }       
    else if (windowWidth >= 1280){
        cssLocation.attr('href','stylesheets/1280-main.css');
        };  
    };

最佳答案

您可以通过检查目标页面名称当前页面名称来避免多次刷新页面。

var xFullPath = window.location.pathname;
var xPageName = xFullPath.substring(xFullPath.lastIndexOf("/") + 1);

function checkWidth(){
    var windowWidth = $(window).width(),
        cssLocation = $('link[href$="main.css"]');

    if (windowWidth <= 240){
        cssLocation.attr('href','stylesheets/240-main.css');
        }
    else if (windowWidth <= 480){
        /*Redirecting point 1*/
        if (xPageName !== "smartPhone-index.html")
        {
        window.location.replace("smartPhone-index.html");
        cssLocation.attr('href','stylesheets/480-main.css');
        }

        }       
    else if (windowWidth <= 768){
        /*Redirecting point 2*/
        if (xPageName !== "index.html")
         {
           window.location.replace("index.html");
           cssLocation.attr('href','stylesheets/768-main.css');
         }
      }       
    else if (windowWidth <= 1024){
        cssLocation.attr('href','stylesheets/1024-main.css');
        }       
    else if (windowWidth >= 1280){
        cssLocation.attr('href','stylesheets/1280-main.css');
        };  
    };

关于javascript - window.location.replace不断重新加载页面,如何停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20173240/

相关文章:

javascript - 自动在页内和通过 DTM 调用 SiteCatalyst s_code

javascript - javascript播放声音不适用于chrome for android

javascript - 在 JavaScript 上请求客户端证书

javascript - 覆盖 Tab 键行为,因此它不会转到下一个字段(只关注实际字段)

javascript - 返回 JsonConvert.SerializeObject(json) [.NET 处理程序] 后在 javascript 上解析 JSON

javascript - Vue.js - 如何在滚动时为我的 div 设置动画

javascript - jquery根据类集选择具有多个类的元素

javascript - 在颜色盒上添加回调以跳过幻灯片的第一张图像

jQuery 在屏幕上一点一点地移动一个 div

jquery - 日常使用的RightJS javascript库