簡體   English   中英

在javascript中將document.stylesheets轉換為路徑數組

[英]Convert document.stylesheets into array of paths in javascript

我在 java 腳本中有一段動態代碼,用於分析頁面上的樣式表。 我有大部分工作,但我有一個掛斷...

我正在檢查某些樣式表是否存在的部分。 MDN 有這樣的說法,“[StyleSheetList] 是一個類似數組的對象,但不能使用 Array 方法迭代。但是它可以......轉換為一個數組。” 它們包括一個示例,其中將對象轉換為一系列規則,但我沒有看到獲取路徑的明確方法。 它還說“styleSheetList[index]”是一種可以訪問的方式。 我嘗試創建這個函數,但它不起作用,總是返回 false...

function checkStyleSheet (styleSheetPath){
    var mysheets=document.styleSheets;
    for (var i = 0, max = mysheets.length; i < max; i++) {
        if (mysheets[i].href == styleSheetPath){
            return true;
        }
    }
    return false;
}

謝謝

JFiddle https://jsfiddle.net/3jsvbwrv/

編輯:就在 for 循環中的 mysheets[i] 的 console.log 返回......

// CSSStyleSheet → http://example.com/example.css
CSSStyleSheet { 
    ownerRule: null,
    cssRules: CSSRuleList[1],
    type: "text/css",
    href: null,
    ownerNode: <style>,
    parentStyleSheet: null,
    title: "",
    media: Object[0],
    disabled: false 
}

編輯 2:注意:在 if 語句中將 mysheets[i].href 更改為 mysheets[i] 並不能解決問題。 example.css 仍會被發現為 false。

編輯 3:我不認為它應該有任何影響,但以防萬一它可能有用,或者提供更廣泛的概述,或者幫助提供上下文......通過這個調用的函數包含那里的 CSS 腳本首先(經驗證有效)...

function addStyleSheet (styleSheetPath){
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = styleSheetPath;
    document.getElementsByTagName("head")[0].appendChild(link);
}

我的最終目標是使這項工作...

function requireStyleSheet (styleSheetPath){
    if (!checkStyleSheet(styleSheetPath)){
        addStyleSheet(styleSheetPath);
    }
}

編輯 4我的測試 html:

<button onmousedown="addStyleSheet('htt://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">Step1‌​</button>
<button onmousedown="requireStyleSheet('http://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css')">S‌​tep 2</button>

編輯 5正如一些測試人員所指出的,代碼按原樣工作。 結果證明我的問題是在我的第二個函數嘗試檢查它的存在之前,被調用的文件還沒有完成加載。

我知道這是一個老問題,但它也是我來尋找相同事物時的第一個搜索結果。 我猜 Javascript 有一些新技巧,因為這就是我現在的工作:

[].slice.call(document.styleSheets).map(e => e.href)

我使用有效的CSS文件作為參數在頁面中運行代碼,返回true 在您的示例中,它確實好像您正在嘗試加載JS文件而不是CSS文件一樣:

<button onmousedown="addStyleSheet('http://momentjs.com/downloads/moment.min.js')">Step1‌​</button>
<button onmousedown="requireStyleSheet('http://momentjs.com/downloads/moment.min.js')">S‌​tep 2</button>

也許您可能考慮讓checkStyleSheet檢查一個哈希值,而不是每次都遍歷每個樣式表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM