是否有一个JQuery函数可以为所选元素提供与另一个元素相同的CSS

Is there a JQuery function to give a selected element the same CSS as another element?

本文关键字:元素 另一个 CSS 函数 JQuery 有一个 是否      更新时间:2023-09-26

我想知道是否有JQuery函数可以用于将CSS从给定元素应用到另一个元素。我说的是精确的CSS;由于继承,没有其他应用。

更具体地说:

<div id="d1">
    <p id="p1">Here is some text.</p>
</div>
<div id="d2">
    <p id="p2">Here is some other text.</p>
    <!-- I want this text in p2 to have the same styling as the text in p1, even after the inheritances of the divs are factored. -->
</div>
<script type="text/javascript">
    $(...).(...); // ??????????????
</script>

如果JQuery有这样的功能,它将为我节省一个小时的时间来尝试使用我自己的样式表(我使用的是一个CMS,它有一个我无法更改的主样式表),以了解如何覆盖/添加一百万个属性。

虽然与Opera不兼容,但这应该可以实现您的目标:http://jsfiddle.net/6o3f3em6/1/

  • 使用getComputedStyle获取目标元素的所有CSS属性
  • 将对象字符串化为CSS
  • 将cssText应用于接收元素

以下是相关代码:

var target = document.querySelector('#p1');
var receiver = document.querySelector('#p2');
var styles   = getComputedStyle(target);
var cssText = '';
for(var style in styles){
    cssText += style+':'+styles[style];
}
receiver.style.cssText = cssText;