我正在创建一个脚本,该脚本会在某些断点处更改 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/