Đoạn code jQuery chuyển thẻ img thành div và style background
23rd Jul 2021- 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>'); t.hide(); p.append(d); d.css({ '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