Đoạn code jQuery chuyển thẻ img thành div và style background

Written by admin
Posted on Fri, 07/23/2021 - 10:34

Share Everywhere

Table of contents
  • IE 8,9,10,11 and EDGE detection
  • used in Bootrap 4
  • take the height of its parent div
  • cliped vertically at 20% of top and horizontally 50% (better for portraits)

Chúng ta có logic như sau. Và yêu cầu chuyển thành style có propertly là background-image: url

<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />

This is code

$('.post-thumb img').each(function(){           // Note: {.post-thumb img} is css selector of the image tag
    var t = $(this),
        s = 'url(' + t.attr('src') + ')',
        p = t.parent(),
        d = $('<div></div>');
        'height'                : 260,          // Note: You can change it for your needs
        'background-size'       : 'cover',
        'background-repeat'     : 'no-repeat',
        'background-position'   : 'center',
        'background-image'      : s

parent div:

height: 584px;
display: block;
background-position: center center;
background-size: cover;
width: 100%;
position: absolute;
overflow: hidden;
background-color: #fff;

child img

object-position: center center;
min-height: 100%;
display: block;
position: absolute;
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
width: auto;
min-width: 100%;
max-width: none;
-o-object-fit: cover; // you can keep them for modern browsers
object-fit: cover; // you can keep them for modern browsers
height: 100%;

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
13 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”