Add CSS content image after <input> element

2019-07-16 14:19发布

问题:

This question already has an answer here:

  • Can I use a :before or :after pseudo-element on an input field? 20 answers

I cannot reach to add an image after an input element for form validation with JQuery. Doesn't work also if I add the class manually on the element...

HTML:

<script type="text/javascript">
      $(document).ready(function(){
          $('#last_name').addClass('cross');
      });
</script>

<label for="last_name">*Last Name:</label>
<input type="text" id="last_name" value="<?=$last_name?>" />

CSS:

.cross:after {
    content:url(/ico/cross.png);
    /* Tried also with:
      content:url('/ico/cross.png');
    AND
      content: '';
      background:url(/ico/no_check.png); */
}

回答1:

The ::after pseudo-element places the 'element' within the element itself 'after' its contents (not after the element), an input is a void element that cannot contain any other HTML. This cannot work, unfortunately. See, for example: "CSS :after pseudo element on INPUT field."

With jQuery, however, you could add a new image (not a background-image, or pseudo-element) using the following (though untested):

$('.cross').after('<img src="ico/cross.png" />');

Simple demo.

References:

  • after().


回答2:

I think you would do better using this route:

Live Demo

CSS:

label[for='last_name'] {
  content: url(https://www.google.com/images/srpr/logo11w.png);
  width: 32px;
  height: 32px;
}

And to distinguish it in writing, use placeholder:

<label for="last_name"></label>
<input name="last_name" placeholder="Last Name" />