如何在移动设备上使用纯 JavaScript 放大单击的图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23641576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enlarge a clicked image with plain JavaScript on a mobile device
提问by Blockspace21
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.
我正在尝试创建单击时会放大的缩略图。目标是将所选缩略图放大到设备的最大宽度。如果单击另一个缩略图,其图像将替换当前所选缩略图的图像。任何时候只能放大一张缩略图。
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(无 jQuery)、CSS 和 HTML 来实现这一点。
JavaScript
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
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
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?
图像确实弹出,但它太大(比设备宽),所以它不适合移动屏幕。我如何使它成为合适的尺寸?
回答by Axel
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.
这将强制图像不大于它所在的容器,并在较小的屏幕上自动缩小。