繁体   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