如何在移动设备上使用纯JavaScript扩大点击的图像 [英] How to enlarge a clicked image with plain JavaScript on a mobile device

查看:93
本文介绍了如何在移动设备上使用纯JavaScript扩大点击的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建缩略图,点击后放大。目标是让选定的缩略图放大到设备的最大宽度。如果单击另一个缩略图,其图像将替换当前所选缩略图的图像。任何时候只能放大一个缩略图。

I'm trying to create thumbnail images that enlarge when clicked. The goal is to have the selected thumbnail enlarge itself to the maximum width of the device. If another thumbnail is clicked, its image will replace that of the currently selected thumbnail. Only one thumbnail can be enlarged at any one time.

图像应该跨越设备的最大宽度。此外,我试图用普通的JavaScript(没有jQuery),CSS和HTML来实现这一点。

The image should span the device's maximum width. Also, I am trying to accomplish this with plain JavaScript (no jQuery), CSS, and HTML.

JavaScript

function showImage(imgName) {
    document.getElementById('largeImg').src = imgName;
    showLargeImagePanel();
    unselectAll();
}
function showLargeImagePanel() {
    document.getElementById('largeImgPanel').style.visibility = 'visible';
}
function unselectAll() {
    if(document.selection) document.selection.empty();
    if(window.getSelection) window.getSelection().removeAllRanges();
}
function hideMe(obj) {
    obj.style.visibility = 'hidden';
}

HTML

<img  src="./Images/image.jpg" alt="1.jpeg" style="cursor:pointer" 
      onclick="showImage('./Images/image.jpg');">
<div id="largeImgPanel" onclick="hideMe(this);">
<img id="largeImg" style="height: 100%; margin: 0; padding: 0;">

CSS

#largeImgPanel {
    text-align: center;
    visibility: hidden;
    position: fixed;
    z-index: 100;
    top: 0; left: 0; 
    width:100%;
    height:100%; 
    background-color: rgba(100,100,100, 0.5);
}

图像确实弹出,但是太大了(比设备),因此它不适合移动屏幕。如何使其尺寸合适?

The image does pop up, but it is too large (wider than that of the device), so it does't fit the mobile screen. How do I make it the right size?

推荐答案

您需要将图像宽度限制为父容器的宽度。

You need to constrain the image width to the width of the parent container.

#largeImg  {
    height: auto;
    max-width: 100%;
}

这会强制图像不大于它所容纳的容器,并在较小的屏幕上自动缩小。

This will force the image to be no bigger than the container it's held in, and automatically scale down on smaller screens.

这篇关于如何在移动设备上使用纯JavaScript扩大点击的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆