我有一个包含许多不同画廊类别的网站,在屏幕宽度低于 1200 像素之前显示较小的缩略图尺寸,之后我想改为显示完整尺寸。
图像显示如下:
<section class="gallery category1">
<img id="cat1img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="cat1img2" src="cat1/small/img-2.jpg" alt="blah">
etc...
</section>
<section class="gallery category2">
<img id="cat2img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="cat2img2" src="cat2/small/img-2.jpg" alt="blah">
etc...
</section>
我想要做的就是使用带有一些 jQuery 的 JS 媒体查询从每个标签中删除“小/”,而不列出每个 img,这样它们就可以自由添加和删除,而无需再次修改代码。
这是我尝试过的,但它并没有改变 img url,尽管它确实触发了我的尺寸更改检查:
function galleryBreak(x) {
if (x.matches) {
$('.gallery').children('img').attr('src').replace('/small','')
console.log('size change check');
};
};
var x=window.matchMedia('(max-width: 1200px)')
galleryBreak(x)
x.addListener(galleryBreak)
答案 0 :(得分:1)
您有多个 (2) 个画廊和多个图像。您需要遍历所有画廊的所有图像。像这样
function changeImagePaths(theGallery) {
var images = theGallery.querySelectorAll('img');
images.forEach( image => {
console.log('Path before: ', image.src)
image.src = image.src.replace('/small','')
console.log('Path AFTER: ', image.src)
});
};
var x=window.matchMedia('(max-width: 1200px)')
var myGalleries = document.querySelectorAll('.gallery')
myGalleries.forEach( gallery => {
if(x.matches) {
changeImagePaths(gallery)
}
});
<section class="gallery category1">
<img id="img1" src="cat1/small/img-1.jpg" alt="blah">
<img id="img2" src="cat1/small/img-2.jpg" alt="blah">
</section>
<section class="gallery category2">
<img id="img1" src="cat2/small/img-1.jpg" alt="blah">
<img id="img2" src="cat2/small/img-2.jpg" alt="blah">
</section>
现在说了这么多,如果您可以更改 HTML,请使用 Responsive images,它将显示您可以在图像标签中正确设置的所有内容,例如:
<img srcset="elva-fairy-320w.jpg,
elva-fairy-480w.jpg 1.5x,
elva-fairy-640w.jpg 2x"
src="elva-fairy-640w.jpg"
alt="Elva dressed as a fairy">
答案 1 :(得分:1)
在窗口上添加 resize
事件侦听器,以便在每个窗口/浏览器调整大小时触发此事件
const galleryBreak = () => {
if (window.matchMedia('(max-width: 1200px)').matches) {
const images = document.querySelectorAll('.gallery img');
Array.from(images).forEach(img => {
const imgSrc = img.src.replace('/small', '');
img.src = imgSrc;
console.log(imgSrc);
});
}
};
window.addEventListener('resize', galleryBreak);