2012-01-18 2 views
6

HTMLStyleElement (document.createElement('style'))에서 CSSStyleSheet 객체 (document.styleSheets[0])를 가져올 수 있습니까?HTMLStyleElement 요소에서 CSSStyleSheet 객체를 가져 오는 방법

문서에 삽입되지 않은 요소에 CSS 규칙을 동적으로 추가하고 싶습니다. 아직 <style> 요소입니다.

+0

당신은 대답을 : [http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript][1] [을 1] : http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript – netadictos

+0

감사합니다 netadictos,하지만 주제는 약간 다릅니다 –

+0

나는 당신이 문서를 복제 할 수 있다고 생각 제거 스타일 시트를 복제하여 새로운 것을 추가하고 객체를 가져 와서 문서 복제본을 다시 제거하십시오. – noob

답변

1

스타일 요소를 문서에 추가하기 전에 규칙을 추가하십시오.

이전 IE 브라우저 notes- 몇 가지 스타일 요소에 자식 노드를 추가 할 수 없습니다, 그래서 그들을 위해 요소의 styleSheet.csstext 속성에 할당합니다. 새 요소를 문서의 머리글에 추가했는지 확인하십시오. 여기 그런

document.head.appendChild(document.createElement("style")).setAttribute("type", "text/css"); 
var mycss = document.styleSheets[document.styleSheets.length-1]; 

입니다 : 여기

function addStyle(css, media1, title1){ 
    var el= document.createElement('style'); 
    el.type= 'text/css'; 
    if(media1) el.media= media1; 
    if(title1) el.title= title1; 
    if(el.styleSheet) el.styleSheet.cssText= css;//IE 
    else{ 
     el.appendChild(document.createTextNode(css)); 
    } 
    //return el without the next line if you want to append it later 
    return document.getElementsByTagName('head')[0].appendChild(el); 

} 

var cs1= [ 
    '#yw_psq, #yw_psq h2{background-color: green; color: white;}', 
    '#yw_psq_div{margin: 1ex; position: relative; text-align: center;}', 
    '#ps_counter{color: white; margin: 1ex 0 0 0; text-align: center;}', 
    '#pzsq_grid button{cursor: pointer; font-size: 1.2em; width: 100%;}', 
    '#delaySpan{font-weight: bold; margin-left: 1em;}' 
] 

addStyle(cs1.join('\n'),'screen','yw_psq'); 
+0

'document.createElement ("style")'는 네임 스페이스가없는 요소를 생성하기 때문에 XHTML5 문서에서 작동하지 않습니다. 즉 요소가 HTMLElement 인터페이스로부터 속성을 상속 받기 때문에 기본적으로 빈 요소가됩니다 특별한 속성은 없습니다. 이 문제를 해결하려면 XHTML 문서에서 'document.createElementNS ("http://www.w3.org/1999/xhtml", "style")'을 사용해야합니다. –

0

삽입 할 요소에 액세스 할 수있는 경우 다른 요소와 마찬가지로 스타일 정보를 추가 할 수 있습니다. 요소가 삽입되면 브라우저는 해당 페이지를 다시 보내고 적용되는 모든 관련 CSS 규칙을 선택합니다. 요소의 스타일을 지정하기 위해 스타일 시트에 액세스 할 필요가 없으므로 요소에 액세스 만하면됩니다.

1

내가 보통합니다 (HTMLStyleElementappendChild에 의해 반환 대신에) 새로운 스타일 시트를 만들 내 자바 스크립트를 MITH 않고 그 CSSStyleSheet 객체 mycss를 얻는 방법이다 스타일 규칙을 추가하는 방법 :

mycss.insertRule("css, selectors { cool: styles; and: stuff; }", mycss.cssRules.length); 

희망이 있습니다.

2

<style> 요소에서 CSSStyleSheet 객체를 가져올 수 있습니다.입니다.

var style = document.createElement('style'); 
document.head.appendChild(style); 
var styleSheet = style.sheet // Will give you the associated CSSStyleSheet 

이 만 <style> 요소가 문서에 추가 된 후 을 작동합니다.

매우 예외적으로 문서화되지 않았고 콘솔에서 훑어 보아 찾기가 매우 어렵습니다. 여기

+0

다른 문서를 만들면 먼저 기본 문서에 적용 할 수 있다고 생각합니다. 'var newDoc = document.implementation.createHTMLDocument(); newDoc.head.appendChild (myStyleElement)'.FF에서는'newDoc.styleSheets [0] .cssRules'를 얻는 데 충분하지만 Chrome이 정의되지 않은 값을 반환하기 때문에 myStyleElement를 요소로 가져와야하므로'.sheet.cssRules'를 추가 할 수있었습니다. (내 프로젝트는 usercript 일 뿐이 기 때문에 다른 브라우저는 보지 못했다.)하지만 네,이'.sheet' 속성에 대해 얼마나 미약한지 알 수 있습니다. –

관련 문제