簡體   English   中英

繼承/擴展 CSS 屬性到另一個元素

[英]Inherit/Extend CSS properties onto another element

jQuery 中將 CSS 屬性從一個元素擴展/繼承到另一個元素的最有效方法是什么?

想要的效果

$('#blah').extendCSSTo('#me') // Is there a plugin or a good way to do this?
$('#me').css({ background: 'blue' });

#me現在將擁有#blah 的所有#blah以及background

CSS:

#blah {
    padding: 5px;
    width: 200px;
    height: 20px;
    border: 1px solid #333;
    font-family: "Verdana";
}

#me {
    position: absolute;
    left: 5px;
    top: 5px;
}

<div id="blah"></div>
<div id="me">test</div>

編輯:這將在插件中使用,因此使用類和簡單地做.addClass不是一個選項

我正在尋找與為插件選項設置默認值相同的效果,但是對於 CSS:

$.extend([css object], [#blah css object], [#me css object])
$('#me').addClass('class');

這可行,但不確定您是否可以使用相對於 ID 的 css。

嘗試這個。

function CloneStyle(sourceID, targetID){
    var myStyle;
    var source = document.getElementById(sourceID);
    var target = document.getElementById(targetID);
    if (window.getComputedStyle) {
        myStyle = window.getComputedStyle(source).cssText;
    }
    else if (source.currentStyle) {
        myStyle = $.extend(true, {}, source.currentStyle);
    } else {
        throw "antique browser!";
    }
    target.style.cssText = myStyle;
}

現在打電話給喜歡。

CloneStyle("blah", "me");
$('#me').css({ background: 'blue' });

在這里小提琴: http://jsfiddle.net/naveen/3FdDp/

如果您要使用 CSS 類而不是 ID 引用,您可以執行以下操作:

$("#me").addClass($("#blah").attr("class"));

這會將類從#blah復制到#me

暫無
暫無

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

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