簡體   English   中英

在jQuery中獲取全局樣式表的值

[英]Getting values of global stylesheet in jQuery

當我在HTML頁面范圍內使用這樣的樣式表定義時

#sideBar {
  float: left;
  width: 27.5%;
  min-width: 275;
  ... 
}

以下代碼不返回CSS定義的width的值:

document.getElementById("sideBar").style.width;

本文中,該函數顯示了檢索正確的值,當我嘗試這樣做時,它並不能真正在跨瀏覽器中工作。 所以我在jQuery中嘗試了類似的方法,但是失敗了。

$("#sideBar").css("width'"); // 1st trial
$("#sideBar").width(); // 2nd trial

我確實獲得了絕對像素寬度, 而不是百分比值27.5。 有沒有辦法獲取百分比值呢?

備注:與SO類似(但不相同)問題: 在jQuery中獲取CSS規則的百分比值

var width = ( 100 * parseFloat($("#sideBar").css('width')) / parseFloat($("#sideBar").parent().css('width')) ) + '%';

引用在jQuery中獲取CSS規則的百分比值

這是小提琴http://jsfiddle.net/jSGTs/

這是我所做的。 由於所有方法都不能真正可靠地運行(跨瀏覽器等),所以我遇到CSS解析器/抽象器了嗎? 如何將樣式表轉換為對象

首先,我打算使用一些功能強大的CSS解析器,例如

  1. JSCSSP
  2. jQuery CSS解析器

既強大,又重量級。 最終我有了自己的小功能

// Get the original CSS values instead of values of the element.
// @param {String} ruleSelector
// @param {String} cssprop
// @returns {String} property of the style
exports.getCssStyle = function (ruleSelector, cssprop) {
    for (var c = 0, lenC = document.styleSheets.length; c < lenC; c++) {
        var rules = document.styleSheets[c].cssRules;
        for (var r = 0, lenR = rules.length; r < lenR; r++) {
            var rule = rules[r];
            if (rule.selectorText == ruleSelector && rule.style) {
                return rule.style[cssprop]; // rule.cssText;
            }
        }
    }
    return null;
};

jQuery中什么也沒有,即使在javascript中也沒有任何直接的方法。 以timofey的答案並運行它,我創建了此函數,該函數可用於獲取所需的任何屬性:

// gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
// domNode - the node to get properties for 
// properties - Can be a single property to fetch or an array of properties to fetch
function getFinalStyle(domNode, properties) {
    if(!(properties instanceof Array)) properties = [properties]

    var parent = domNode.parentNode
    if(parent) {
        var originalDisplay = parent.style.display
        parent.style.display = 'none'
    }
    var computedStyles = getComputedStyle(domNode)

    var result = {}
    properties.forEach(function(prop) {
        result[prop] = computedStyles[prop]
    })

    if(parent) {
        parent.style.display = originalDisplay
    }

    return result
}

這里使用的技巧是隱藏其父級,獲取計算出的樣式,然后取消隱藏父級。

當您需要全局樣式表中定義的確切值時,您必須訪問樣式元素中的規則。
這不是在jQuery中實現的。

IE: 規則收集
其他: CSSRuleList (也可能受IE8或9支持,無法確切告訴您)

暫無
暫無

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

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