[英]How can I make <img> tag show a full size image when clicked, while href of that tag can change?
我正在尝试创建一个包含主图像和下面较小图像的画廊,通过单击主图像,它应该在新的 window 中打开它,如果单击较小的图像,它应该将主图像更改为您单击的图像和它也改变了href,所以最后,主图像动态改变了href和src属性。
下面你可以看到我是如何尝试这样做的,它正在工作,但是当我按下较小的图像时,它们不仅会更改主要图像,而且还会在新的 window 中打开。 我该怎么办,只有主图像可以打开新的 window?
function transitSrc(imgs) { // Get the expanded image var expandImg = document.getElementById("expandedImg"); // Use the same src in the expanded image as the image being clicked on from the grid expandImg.src = imgs.src; //Get the href of expanded image var fullImage = document.getElementById("viewFullImg"); //Use the same href in the expanded image as the image being clicked on from the grid fullImage.href = imgs.href; // Show the container element (hidden with CSS) expandImg.parentElement.style.display = "block"; }
.product-gallery { list-style: none; padding: 0; width: 100%; margin: 10px 0 0; }.product-gallery li { display: inline-block; width: 15%; margin: 0 5px; }.product-gallery li:first-child { margin-left: 0; }
<div class="container"> <div class="row"> <div class="col-sm-6 mb-sm-40"> <div class="gallery"> //main image <a id="viewFullImg" href="https://picsum.photos/id/1060/536/354?blur=2"> <img id="expandedImg" src="https://picsum.photos/id/1060/536/354?blur=2" style="width:50%"> </a> </div> //smaller images <ul class="product-gallery"> <li> <a href="https://picsum.photos/id/870/536/354?grayscale&blur=2"> <img style="width:80%" src="https://picsum.photos/id/870/536/354?grayscale&blur=2" onclick="transitSrc(this);"></a> </li> <li> <a href="https://picsum.photos/id/1060/536/354?blur=2"> <img style="width:80%" src="https://picsum.photos/id/1060/536/354?blur=2" onclick="transitSrc(this);"></a> </li> <li> <a href="https://picsum.photos/id/870/536/354?grayscale&blur=2"> <img style="width:80%" src="https://picsum.photos/id/870/536/354?grayscale&blur=2" onclick="transitSrc(this);"></a> </li> </ul> </div> </div> </div>
为了防止a
标签进行重定向,您可以覆盖onClick
防止其默认行为:
function prevent(event) { event.preventDefault(); }
<a href="https://stackoverflow.com" onClick="prevent(event)">Press here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.