我已经在论坛上搜索过了,但找不到这样的内容。
我有一个页面设置了一堆图像(画廊类型的东西),当他们用户点击图像时,它会将大小从 200x200 缩略图更改为全尺寸 600x600。
我的问题是,可以继续单击这些图像,而前一个图像将保持放大状态。我想将扩展图像的数量限制为一个。 这是javascript:
function toggleSize(image) {
if (image.style.width != "600px") {
image.style.width = "600px";
image.style.height = "600px";
} else {
image.style.width = "200px";
image.style.height = "200px";
}
每张图片的html如下:
<img class="galleryImage" src="../m/54.jpg" onclick="toggleSize(this)" />
galleryImage 类如下所示:
.galleryImage {
margin: -2px -2px -3px -2px;
width: 200px;
height: 200px;
}
从本质上讲,理论上,我希望类 galleryImage 的每个元素都重置为其原始宽度和高度 200x200。
如有任何帮助,我们将不胜感激。
最佳答案
您可以使用 getElementsByClassName
搜索给定类别的所有图像(并丢弃当前类别)并通过循环结果将它们恢复到起始状态。
Returns an array of all child elements which have any of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.
在此之后,您可以调用切换函数。
代码:
function resetImages(classToFind, image) {
var elems = document.getElementsByClassName(classToFind);
if (!elems) return;
for (var i = elems.length - 1; i >= 0; i--) {
var elem = elems[i];
if (elem === image) continue
elem.style.width = "200px";
elem.style.height = "200px";
}
}
function toggleSize(image) {
resetImages('galleryImage',image);
if (image.style.width != "600px") {
image.style.width = "600px";
image.style.height = "600px";
} else {
image.style.width = "200px";
image.style.height = "200px";
}
}
关于javascript - 重置类中所有图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21474616/