JavaScript缩略图是现代网站不可或缺的一部分。通过使用JavaScript编写代码,可以将完整的图像转换为较小的图像,并在页面上显示它们,以便用户可以更快地加载。
下面是JavaScript缩略图的示例:
<!DOCTYPE html> <html> <head> <title>缩略图示例</title> <style> .thumbnail { border: 1px solid #ddd; padding: 10px; margin: 10px; } .thumbnail img { max-width: 100%; height: auto; } </style> </head> <body> <div class="thumbnail"> <img src="img/full-image-1.jpg" alt="Full image 1"> </div> <div class="thumbnail"> <img src="img/full-image-2.jpg" alt="Full image 2"> </div> <div class="thumbnail"> <img src="img/full-image-3.jpg" alt="Full image 3"> </div> <script type="text/javascript"> var thumbnails = document.querySelectorAll('.thumbnail'); for (var i = 0; i < thumbnails.length; i++) { var thumbnail = thumbnails[i].querySelector('img'); var fullImageSrc = thumbnail.src; thumbnail.src = thumbnail.src.replace('.jpg', '_thumb.jpg'); thumbnail.setAttribute('data-full-image-src', fullImageSrc); thumbnail.addEventListener('click', function() { var fullImageSrc = this.getAttribute('data-full-image-src'); var fullImage = document.createElement('img'); fullImage.src = fullImageSrc; fullImage.addEventListener('load', function() { var width = fullImage.width; var height = fullImage.height; var maxWidth = 800; var maxHeight = 600; if (width > maxWidth) { height = height * maxWidth / width; width = maxWidth; } if (height > maxHeight) { width = width * maxHeight / height; height = maxHeight; } var modal = document.createElement('div'); modal.style.position = 'fixed'; modal.style.zIndex = '9999'; modal.style.top = '0'; modal.style.left = '0'; modal.style.width = '100%'; modal.style.height = '100%'; modal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)'; modal.style.display = 'flex'; modal.style.justifyContent = 'center'; modal.style.alignItems = 'center'; var modalImage = document.createElement('img'); modalImage.src = fullImageSrc; modalImage.style.maxWidth = width + 'px'; modalImage.style.maxHeight = height + 'px'; modal.appendChild(modalImage); modal.addEventListener('click', function() { document.body.removeChild(modal); }); document.body.appendChild(modal); }); }); } </script> </body> </html>
以上代码展示了如何使用JavaScript创建缩略图。JavaScript在页面加载时对缩略图进行处理,将原始图像替换为缩略图。
当用户点击缩略图时,JavaScript会将原始图像加载到页面上。如果原始图像太大,则JavaScript会自动将其缩小到适当的大小。
此示例使用JavaScript的事件处理程序,当用户单击图像时,将创建一个模态框,其中包含原始图像。用户可以关闭模态框来返回缩略图视图。
JavaScript缩略图不仅使页面加载更快,而且还可以提高页面的用户友好性。用户可以更快地获取所需信息,并有机会查看更多细节。