简体   繁体   中英

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 ui allows to float left/right images, applying an inline style to IMG tags.

<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:

.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. (I know that probably also this.addClass() is wrong, but neither alert() is never fired at the moment)

Can you help me?

Use attr instead of css for selecting inline styled objects:

$('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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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