Заставить jQuery применять CSS-переменные к вложенным / рекурсивным объектам? - PullRequest
0 голосов
/ 15 мая 2019

Я делаю функцию для рекурсивного распределения любого значения CSS, установленного в родительском DIV, всем вложенным дочерним DIV.

Так, например, если верхний DIV имеет "border-radius" "4px", функция будет рекурсивно проходить через все вложенные дочерние элементы в верхнем DIV и копировать то же значение для данного тега. В то же время затронутые элементы будут возвращены в хронологическом массиве. Таким образом, первый элемент в массиве - это первый найденный дочерний элемент, а последний элемент в массиве - последний дочерний элемент самого глубокого гнезда.

Но при этом возникают два неожиданных условия.

Почему Firefox игнорирует изменения отступов, где Safari меняет отступы?

Почему высота, которая была установлена ​​на "100%" в верхнем элементе, изменилась на абсолютную высоту "142px" в последнем объекте?

Я поместил подробные комментарии в коде и заставил его шаг за шагом предупреждать некоторые промежуточные переменные. Справа показано необработанное дерево DIV, слева обработанное дерево.

Фрагмент, показанный ниже, лучше всего виден в полноэкранном режиме:

$(document).ready(function(){
var parent_id = '#top_div';

// now apply the padding to all siblings of top div
var result = recusiveCopyCSS($(parent_id),'padding');

// just to check if all nested divs were processed alert count
alert("Total nested DIVs found "+result.length);

// now set the border-radius progressively for all object in result
var radius = 0;
$(result).each(function(){ // for each object in result
  radius=radius+6;
  $(this).css('border-radius',radius+"px"); // apply calculated radius
});

var first_child = result.shift();
var last_child = result.pop();

// now set the height of first nested DIV
$(first_child).css('height','100%');

// now apply the height to all siblings of first child
var result = recusiveCopyCSS($(first_child),'height');

// now apply the box-sizing to all siblings in top div
var result = recusiveCopyCSS($(parent_id),'box-sizing');

// just to check if the deepest DIV received correct height, should be '100%'
alert("The deepest height is "+$(last_child).css('height'));

// now change the top padding and apply it again to all children
$(parent_id).css('padding','8px');
var result = recusiveCopyCSS($(parent_id),'padding');

// just to check if the deepest DIV received correct padding, should be '8px'
alert("The deepest padding is now "+$(last_child).css('padding'));


function recusiveCopyCSS(element,csstag){
	var array = []; // empty array for affected objects to be returned
	var cssval = element.css(csstag); // take the value of the parent from its css
	var children = element.children(); // look for all children of the parent
	  children.each(function(){ // for each child
		array.push($(this)); // add child to be returned
		$(this).css( csstag,cssval ); // apply parent's css value to the child
		var recurse = recusiveCopyCSS($(this),csstag); // look for more children inside child
		$.merge( array, recurse ); // merge children of child into affected objects
	  });
	return array; // returns affected objects as linear array
}
});
#top_div
{
  background-color: #3C0; 
  padding:4px; 
  box-sizing:border-box; 
  text-align:center;
}

#duplicate_div
{
  background-color: #3C0; 
  box-sizing:border-box; 
}
<script  type="text/javascript" src="//code.jquery.com/jquery-3.4.0.js"></script>


<div id="duplicate_div" style="width:150px; height:150px; float:right">
    top raw	
    <div id="sub_div_1" style="background-color: #CC0">
        level1
        <div id="sub_div_2" style="background-color: #FC3">
            level2
            <div id="sub_div_3" style="background-color: #3CC">
                level3
                <div id="sub_div_4" style="background-color: #FF0">
                    level4
                </div>
            </div>
        </div>
    </div>
</div>

<div id="top_div" style="width:150px; height:150px; float:left">
    top	processed
    <div id="sub_div_1" style="background-color: #CC0">
        level1
        <div id="sub_div_2" style="background-color: #FC3">
            level2
            <div id="sub_div_3" style="background-color: #3CC">
                level3
                <div id="sub_div_4" style="background-color: #FF0">
                    level4
                </div>
            </div>
        </div>
    </div>
</div>

Ожидаемый результат: (A) все вложенные DIV остаются в пределах высоты родительского контейнера и остаются относительно него, и (B) изменение заполнения также изменяется в Firefox.

...