2010-08-11 16 views
0

我需要獲取類的id屬性並應用基於該id的樣式。MooTools 1.1,如何獲得類的id和應用樣式

因此,例如,每3個列表項與類「錯字」,一個ID爲「應用程序」,另一個ID爲「application_osx」,最後ID爲「application_osx_terminal」

類「錯字」由CSS處理,但我需要根據ID名稱分配背景圖像。

因此,如果ID恰好是「application_osx」或「someotherid」,它會自動具有適用於它這個CSS

#application_osx { background: url(/path/to/image/application_osx.png) } 
#someotherid { background: url(/path/to/image/someotherid.png) } 

我試圖用MooTools的1.1這一點。

我想這應該是這樣的準系統

<html> 
    <head> 
    <title>Blah</title> 
    <script src="path/to/mootools.js"></script> 
    <script> 
    A SCRIPT THAT PRINTS OUT: 
    #application_osx { background: url(/path/to/image/application_osx.png) } 
    #someotherid { background: url(/path/to/image/someotherid.png) } 
    BASED ON THE CLASS "TYPO" 
    </script> 
    </head> 
    <body> 
    <ul> 
    <li id="application_osx" class="typo">Application OSX</li> 
    <li id="someotherid" class="typo">Someotherid</li> 
    </ul> 
    </body> 
    </html> 

回答

0

$$( '錯字 ')。每個(函數(EL){ el.setStyle(' 背景圖片',「URL(/ path/to /'+ el.id +'。png)') });

應該做的伎倆,如果我沒有理解好...

+0

變化到'VAR ID = el.get( 「ID」) ;如果(id)el.setStyle(... + id +)' - 儘管我不認爲他的意思恰恰是 – 2010-08-12 09:53:09

+1

get('id')已在1.2中引入,請參閱http://docs111.mootools.net/ Native/Element.js,之前是getProperty('id')... – tonio 2010-08-12 11:22:34

+0

是真的,我完全錯過了問題主題中的mootools版本...通過創建一種風格,確保未來在DOM中使用這些id添加和刪除元素將自動進行樣式設計,而不必每次都運行代碼來進行樣式設計。 – 2010-08-12 12:11:19

0

爲什麼你不能定義你的CSS文件中的規則?如果你需要動態生成規則和附加到文件頭,那麼你需要像這樣

爲mootools的1.2.x的 http://www.jsfiddle.net/dimitar/G5ywF/1/

var StyleWriter = new Class({ 
    // css classes on the fly, based on by Aaaron Newton's version 
    createStyle: function(css, id) { 
     try { 
      if (document.id(id) && id) return; 

      var style = new Element('style', {id: id||'',type:'text/css'}).inject(document.getElement('head')); 
      if (Browser.Engine.trident) 
       style.styleSheet.cssText = css; 
      else 
       style.set('text', css); 

     } catch(e) { 
      console.log("failed:", e); 
     } 
    } 
}); 

使用:

new StyleWriter().createStyle("#rule { blah; }\n#rule2 { blah... }\n", "mystyles"); 

編輯它剛剛讓我注意到你正在使用mootools 1.11所以

http://www.jsfiddle.net/G5ywF/4/

類版本爲1.11略有改動:

var StyleWriter = new Class({ 
    // css classes on the fly, based on by Aaaron Newton's version 
    createStyle: function(css, id) { 
     try { 
      if ($(id) && id) return; 

      var style = new Element('style', {id: id||'',type:'text/css'}).inject(document.getElement('head')); 


      if (window.ie) 
       style.styleSheet.cssText = css; 
      else 
       style.setHTML(css); 

     } catch(e) { 
      console.log("failed:", e.message); 
     } 
    } 
}); 

在FF 3.6測試的1.11類,鉻5和IE7

+1

是的,不確定Gabe想要什麼... 順便說一句,你的代碼將需要一些修復與1.1工作... – tonio 2010-08-12 11:25:55

+0

哦是啊mootools 1.11(/我拍拍額頭) – 2010-08-12 11:59:51