2017-02-13 65 views
0

我有一个HTML标记与一个孩子,每个都有他们的一种风格。如何合并两个div风格?

<div style="font-size:12px;color:red"> 
    <div style="color:blue">...</div> 
</div> 

我想合并这两个标签,结果没有任何变化。我的意思是孩子的风格必须击败父母的风格。在这种情况下,结果必须为:

<div style="font-size:12px;color:blue">...</div> 

我该怎么做?

编辑:

我有两个cssText,我想将它们合并在一个字符串,把它们当做作风ATTR。在上面的例子中,我有 var st1=font-size:12px;color:red;var st2=color:blue; ,我想合并st1和st2优先。

+0

['$()的.css()'](http://api.jquery.com/css/) – empiric

+0

@Naser_Yousefi你的问题有点不清楚。 HTML默认会这样做。内联样式已经具有最高的优先级,并且类似于字体大小的内容应该已经从父级继承。你能否提供一个例子来说明你所遇到的问题,以便我有更多的背景知识? –

+0

@LucasShanley请参阅编辑后的版本。 –

回答

1

<div id=parent style="font-size:12px; color:red"> 
    <div id="child" style="color:blue">text</div> 
</div> 

我添加的ID只是为了可以很容易地抓住这些元素的HTML,还有很多其他的方法可以做到这一点为好。

和这里的JS

parentClass = document.getElementById("parent").style.cssText; 
childClass = document.getElementById("child").style.cssText; 

document.getElementById("parent").style.cssText = parentClass+childClass; 

写的代码非常容易理解的风格。现在父元素将具有父级和子级的类。如果任何一个类重复,那么子类的样式将被应用,因为它是最后写的(这就是CSS的工作方式)。

最后,如果你愿意,你可以使用removeChild()去除子元素。

0

mergeStyledElements函数中使用jQuery选择器。将孩子设置为小学,将父母设置为辅助,并将孩子的文本推送给父母,移除孩子,并将偏向孩子样式的样式合并到父母身上。

var pushStyleStrings = function(str1, str2){ 
 
\t let styleStr = ''; \t 
 
\t function format(str){ 
 
\t \t let rtn = {}; 
 
\t \t str = str.replace(/\s+|\;$/g,'').split(';'); 
 
\t \t $.each(str,function(k,v){ 
 
\t \t \t rtn[v.split(':')[0]] = v.split(':')[1]; 
 
\t \t }); 
 
\t \t return rtn; 
 
\t } 
 
\t function zipObj(obj1, obj2){ 
 
\t \t rtn = obj2; 
 
\t \t $.each(obj1,function(k,v){ 
 
\t \t \t rtn[k] = v; 
 
\t \t }); 
 
\t \t return rtn; 
 
\t } 
 
\t $.each(zipObj(format(str1),format(str2)),function(k,v){ 
 
\t \t styleStr += k + ":" + v + ";"; 
 
\t }); 
 
\t 
 
\t return styleStr; 
 
\t 
 
} 
 

 
var mergeStyledElements = function(primary, secondary){ 
 
    
 
    let $primary = $(primary), 
 
     $secondary = $(secondary), 
 
     $style = pushStyleStrings($primary.attr('style'), $secondary.attr('style')), 
 
     $text = $primary.text(); 
 

 
     $secondary.html($text).css($style); 
 
} 
 

 
mergeStyledElements('#primary', '#secondary');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="secondary" style="font-size:12px;color:red;"> 
 
    <div id="primary" style="color:blue;">...</div> 
 
</div>