如何检查元素是否具有CSS,如果有,请使用它们更新其父元素?

时间:2020-06-25 12:44:26

标签: jquery css

我需要检查<img>是否已定义了内联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标签将为floatmargin包含CSS,并且两者都为somethime或都不包含。我上面的代码仅适用于一条规则。

有人可以告诉我如何针对这两个CSS规则吗?

2 个答案:

答案 0 :(得分:1)

您可以简单地检查图像是否具有任何floatmargin属性,然后使用以下值设置父项:

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>

请注意:

  • 如果元素上没有应用float,则$(this).css('float')返回none
  • 如果元素上没有应用margin-top,则$(this).css('margin-top')返回0px,依此类推。

因此,我们只是使用此逻辑来更新父CSS。

答案 1 :(得分:0)

您可以使用jquery.copycss.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
相关问题