我正在创建一个脚本,可以在某些断点处更改CSS,并在2个精确点重定向到另一个页面。
更改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');
};
};
答案 0 :(得分:1)
请勿使用javascript,请使用CSS media queries。
直接在链接标记中:
<link rel="stylesheet" media="screen and (max-width: 240px)" href="stylesheets/240-main.css" />
<link rel="stylesheet" media="screen and (min-width: 241px) and (max-width: 480px)" href="stylesheets/480-main.css" />
<link rel="stylesheet" media="screen and (min-width: 481px) and (max-width: 768px)" href="stylesheets/768-main.css" />
<!-- etc... -->
或直接在CSS中:
@import url(stylesheets/240-main.css) (max-width:240px);
@import url(stylesheets/480-main.css) (min-width:241px) and (max-width:480px);
@import url(stylesheets/768-main.css) (min-width:481px) and (max-width:768px);
/* etc... */
浏览器将自动加载/更改样式表,页面加载和窗口大小调整期间。
答案 1 :(得分:1)
您可以通过refreshing
查看target page name
来多次current page name
页面。
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');
};
};