简体   繁体   English

根据内联样式的值,将“内联样式”替换为“ css类”

[英]Replace “inline style” with a “css class” depending by value of its inline style

My site has CMS, so users can directly insert texts and images. 我的网站具有CMS,因此用户可以直接插入文本和图像。 CMS ui allows to float left/right images, applying an inline style to IMG tags. CMS ui允许浮动左/右图像,将内联样式应用于IMG标签。

<img src='...' style='float:left'>

I would like to detect when an IMG has a float:left/right style and replace it with a class in order to declare more properties for it like the following example: 我想检测IMG何时具有float:left/right样式,并将其替换为一个类,以便为其声明更多属性,如以下示例所示:

.floated-left
{
  float:left;
  margin-right:20px;
  border-left:solid 5px red;
  ....
}

I thought about something like this: 我想到了这样的事情:

    if ( $("article").find('img').css('float') == 'left')
    {
       this.addClass('floated-left');
    }

But seems that "if clause" never be true. 但是似乎“ if子句”永远不会成立。 (I know that probably also this.addClass() is wrong, but neither alert() is never fired at the moment) (我知道this.addClass()也可能是错误的,但是现在都不会触发alert()

Can you help me? 你能帮助我吗?

Use attr instead of css for selecting inline styled objects: 使用attr而不是css来选择内联样式的对象:

$('article img').each(function() {
   if ( $(this).attr('style') == 'float:left') {

      $(this).removeAttr('style').addClass('floated-left');
   }
});

if some of object's style is different, try this way: 如果某些对象的样式不同,请尝试以下方法:

$('article img').each(function() {
   if ( $(this).attr('style').indexOf('float:left') > -1 ) {

      var targetedStyle = $(this).attr('style').replace('float:left','');
      $(this).attr('style',targetedStyle).addClass('floated-left');
   }
});

In order to apply more declarations, you could simply achieve that by pure CSS: 为了应用更多的声明,您可以简单地通过纯CSS实现:

img[style*="float:left"],
img[style*="float: left"] {
    margin-right : 20px;
    border-left  : solid 5px red;
}

You could play with CSS attribute selectors to select the valid image/element. 您可以使用CSS属性选择器来选择有效的图像/元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM