簡體   English   中英

有沒有辦法找到所有使用樣式中的視口單位的HTML元素?

[英]Is there a way to find all HTML elements that use viewport units in their styles?

我正在構建一個編輯器工具,對於某些功能,它需要調整大小/縮小視口以在頁面上顯示更多部分。

我無法控制HTML / CSS / JS的輸入所有CSS都是來自link標記的外部CSS

問題是HTML元素在樣式中使用vh作為heightmin-height

是否可以在DOM中搜索分配了vh樣式的元素?

我嘗試使用getComputedStyle但正如函數名稱所建議的那樣,它返回“計算”樣式,例如,如果我有一個height80vh的部分

getComputedStyle(el).height
// will return the computed value which is on my screen "655.2px"

我希望實現的是找到這些元素,並在“縮小”視圖期間臨時為它們分配計算值。

正如我上面提到的,樣式是外部的,因此使用style屬性不會提供我想要的東西。

經過一些研究,並感謝fubar的評論 ,他使用document.styleSheets我指出了答案,因此我能夠提出一種滿足我需要的解決方案。

function findVhElements() {
    const stylesheets = Array.from(document.styleSheets)
    const hasVh = str => str.includes('vh');
    // this reducer returns an array of elements that use VH in their height or min-height properties 
    return stylesheets.reduce( (acc,sheet) => { 
        // Browsers block your access to css rules if the stylesheet is from a different origin without proper allow-access-control-origin http header
        // therefore I skip those stylesheets 
        if (!sheet.href || !sheet.href.includes(location.origin)) return acc
        // find rules that use 'vh' in either 'minHeight' or 'height' properties
        const targetRules = Array.from(sheet.rules).filter( ({style}) => style && (hasVh(style.minHeight) || hasVh(style.height)) )
        // skip if non were found
        if (!targetRules.length) return acc;
        // return elements based on the rule's selector that exits on the current document 
        return acc.concat(targetRules.map( ({selectorText}) =>  document.querySelector(selectorText) ).filter( el => el) ) 
    }, [])
}

該解決方案適用於我的情況,因為樣式來自與腳本相同的來源,如果您要處理來自其他來源的樣式,我建議您實施一個后端解決方案,或者確保其他來源提供的HTTP標頭允許您獲取內容

暫無
暫無

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

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