我需要检查
是否定义了内联css
属性,如果是,它需要用这些css
更新其父级,并需要删除原始css声明。
我是这样尝试的:
var $el = $('.article > img');
$el.each(function () {
if ($(this).css("float") == "left") { $(this).parent().css("float","left"); }
if ($(this).css("float") == "right") { $(this).parent().css("float","right"); }
})
我的img标记将有float
或margin
和somethime的css,它们都有或没有。 我上面的代码只适用于一个规则。
有人能告诉我如何同时执行CSS
规则吗?
您只需检查图像是否具有任何float
或margin
属性,然后使用这些值设置父级,如:
null
var $el = $('.article > img');
$el.each(function() {
const float = $(this).css('float')
const marginT = $(this).css('margin-top')
const marginL = $(this).css('margin-left')
const marginR = $(this).css('margin-right')
const marginB = $(this).css('margin-bottom')
// Set the css to the parent based on child img
if (float !== 'none') $(this).parent().css("float", float);
if (marginT !== '0px' && marginT !== '')
$(this).parent().css("margin-top", marginT);
if (marginL !== '0px' && marginT !== '')
$(this).parent().css("margin-left", marginL);
if (marginR !== '0px' && marginT !== '')
$(this).parent().css("margin-right", marginR);
if (marginB !== '0px' && marginT !== '')
$(this).parent().css("margin-bottom", marginB);
// Remove the original image css
$(this).removeAttr('style');
})
.article { border: 1px solid red}
img {width: 50px;height: 50px}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="article">
<img alt="Image 1" style="float:left" />
</div>
<div class="article">
<img alt="Image 2" style="margin: 5px 70px" />
</div>
<div class="article">
<img alt="Image 3" style="float:right;margin: 10px" />
</div>
您可以使用jquery.copycs.js插件。
$('#some-element').copyCSS('#another-element'); // copy all styles
$('#some-element').copyCSS('#another-element', ['top', 'left']); // copy just top and left
$('#some-element').copyCSS('#another-element', null, ['top', 'left']); // copy everything except top and left