Hello, I need a function that will check the image in each .news-img-area block, and if this image has a height greater than 500, then change the height of this image to 500. thanks
- why function? if you can write "max-height: 500px" in css - grnch
|
2 answers
Why Javascript:
.news-img-area img { max-height: 500px; width: auto; } But, if that:
const styleMutation = () => ( [].forEach.call( document.querySelectorAll('.news-img-area img'), (el) => (Object.assign(el.style, { maxHeight: '500px', width: 'auto'} )))) or, literally following your question:
const evilMutation = () => ( [].forEach.call( document.querySelectorAll('.news-img-area img'), (el) => ((el.offsetHeight > 500) && (el.height = 500)))) But here it is necessary to make sure that the images were fully loaded by that moment and the value of innerHeight already innerHeight . Also, CSS styles visually overlap the height value, i.e. better to use them.
|
$('img').each(function(i,elem){ if ($(this).height() > 100) $(this).css({'height' : '100px'}); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img src="http://galerey-room.ru/images/0_3d5b5_7f4a5b0b_orig.png" /> <br> <img src="http://www.plandmsc.com/images/pictures/personalPictures/yellow-gerbera-500x500.jpg" /> |