简体   繁体   English

单击缩略图时,javascript画廊不显示主图像

[英]javascript gallery not displaying main image when thumbnails clicked

I'm wanting to create a gallery which displays a main image when the thumbnails are clicked. 我想创建一个画廊,当单击缩略图时将显示一个主图像。 When clicked the thumbnails rather than altering the image in the webpage take the user to the file where the image is kept and display it in the top right corner. 单击缩略图而不是更改网页中的图像时,会将用户带到保存图像的文件,并在右上角显示该文件。

No idea why this is happening ? 不知道为什么会这样吗? Any suggestions where I'm going wrong and how to fix this ? 有什么建议可以解决我的问题吗?

<img id="veiwer" src="images/motorbike-girl.jpg" />
<div id='thumbs'>
   <a href='images/chicks.jpg' onclick="gallery(this);"><img src='images/chicks-
   thumb.jpg'/></a>
   <a href='images/motorbike-girl.jpg' onclick="gallery(this);"><img 
   src='images/motorbike-girl-thumb.jpg'/></a>                                                
   <a href='images/yamaha-thumb.jpg' onclick="gallery(this);"><img              
   src='images/yamaha.jpg'/></a>    
</div>


         function gallery(change) {

          document.getElementById('viewer').src = change.href;
         }

The problem occurs because of the default behavior of the anchor tag : by default, when you click a link, you get to the page/document it's pointing to. 发生此问题是由于锚标记的默认行为:默认情况下,单击链接时,您会到达它所指向的页面/文档。 So, in your javascript you would need to tell "Don't run the default behavior, only what I want to do". 因此,在您的JavaScript中,您需要告诉“不要运行默认行为,只运行我想做的事”。 It's done through the preventDefault() method of the event. 这是通过事件的preventDefault()方法完成的。

cfr this fiddle for a working example, where I removed also the inline javascript (= onclick attribute). cfr 这个小提琴为一个工作示例,在这里我也删除了内联javascript(= onclick属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM