2017-05-08 1 views
0

페이지가로드되는 동안 스타일 시트를 핫 스왑하는 방법을 찾고 있습니다. 여기 내 현재 솔루션입니다, 그것은 작동하지만 몇 가지 제한 사항/문제가 있습니다.페이지를 다시로드하지 않고도 테마 스타일 시트를 교환하는 우아한 방법

HTML 헤드 :

<link id="theme" href="themes/theme1.css" rel="stylesheet" type="text/css"> 

JS :

themes = [ 
    "themes/theme1.css", 
    "themes/theme2.css" 
]; 

function themeSwitch() { 
    var currentTheme = $("#theme").attr('href'); 
    var themeID = themes.indexOf(currentTheme); 
    themeID = (themeID + 1) % themes.length; 
    $("#theme").attr('href', themes[themeID]); 
} 
브라우저가 추가 GET 요청을 필요로이 방법 내 문제는 함수가 변화를 호출 할 때입니다 인스턴트하지

CSS 파일. 또 다른 문제는 테마를 사용하지 않고 페이지를 사용하는 동안 사용자가 일시적으로 연결을 끊는 경우입니다. 대체 스타일 시트이 쉽게

+0

가능한 [jQuery를 사용하여 CSS 스타일 시트를 전환하려면 어떻게합니까?] (http://stackoverflow.com/questions/7846980/how-do-i-switch-my-css-stylesheet-using-jquery) – Qhuea

+0

@ Qhuea 그 문제의 해결책은 테마가 전환 될 때마다 GET 요청이 필요한 것과 동일한 문제입니다. – luctowers

답변

2

사용

<link id="theme" href="themes/theme1.css" rel="stylesheet" type="text/css"> 
<link id="alttheme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css"> 

function themeSwitch() { 
    var t1 = document.getElementById('theme'); 
    var t2 = document.getElementById('alttheme'); 
    t1.disabled = !t1.disabled; 
    t2.disabled = !t1.disabled; 
} 

보다 일반적인 테마

<link class="theme" href="themes/theme1.css" rel="stylesheet" type="text/css"> 
<link class="theme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css"> 
<link class="theme" href="themes/theme3.css" rel="alternate stylesheet" type="text/css"> 

var currentTheme = 0; 
var themes = [].slice.call(document.querySelectorAll('link.theme')); 

function themeSwitch() { 
    currentTheme = (currentTheme + 1) % themes.length; 
    themes.forEach(function(theme, index) { 
     theme.disabled = (index !== currentTheme); 
    }); 
} 

의 수를 할 수 있습니다 방법, 그리고 모두의 마지막 (이 개 주제에 대한 예는 간단하다) jQuery에 태그를 지정하지 않았더라도 jQuery를 코드에서 사용하므로 jQuery 세트를 위해 다음과 같이 설정해야합니다.

<link class="theme" href="themes/theme1.css" rel="stylesheet" type="text/css"> 
<link class="theme" href="themes/theme2.css" rel="alternate stylesheet" type="text/css"> 
<link class="theme" href="themes/theme3.css" rel="alternate stylesheet" type="text/css"> 

var currentTheme = 0; 
var themes = $('link.theme'); 

function themeSwitch() { 
    currentTheme = (currentTheme + 1) % themes.length; 
    themes.each(function(index, theme) { 
     theme.disabled = (index !== currentTheme); 
    }); 
} 
+0

신난다, 고마워! Jquery로 표시했습니다. – luctowers

+0

jQuery 태그를 보지 못했습니다. 미안 해요 : p –