繁体   English   中英

使用Java单击时显示图库中的图像

[英]Display Image from Gallery On Click using Javascript

我正在尝试学习Javascript,我想编写一个脚本,该脚本允许用户单击图库中的图像(图像恰好是水獭),并将该图像聚焦在页面的中央。 我的目标是使脚本循环浏览页面上的每个图像,并为每个图像赋予功能,以使聚焦图像的源变为用户单击时所单击图像的源。 我一直没有成功。

我相关的html代码是:

      <div class="gallery">
        <img src= "otter1.png")/>
        <img src= "otter2.png")/>
        <img src= "otter3.png")/>
        <img src= "otter4.png")/>
        <img src= "otter5.png")/>
        <img src= "otter6.png")/>
      </div>

    <div class="focus">
      <img id="focus" src="otter1.png">
    </div>

相关的CSS代码:

.gallery {
    margin: 5px;
    border: 1px solid #ccc;
    float: left;
    width: 180px;
}

.gallery img:hover {
    border: 1px solid #777;

}


.gallery img {
    width: 100%;
    height: auto;
}

.focus {
  position: fixed;
  text-align: center;
  vertical-align: center;
  margin-left: 50px;
  margin-top: 100px;
  border: 4px solid white;
}

最重要的是javascript:

window.onload = function() {
    var imgs = document.getElementsByTagName('img');
    for(var i = 0; i < imgs.length; i++) {
        var img = imgs[i];
        img.onclick = function() {
            newSrc = img.getAttribute('src'); /* problem line ?*/
            focus = document.getElementById('focus');
            focus.src = 'newSrc';
        }
    }
}

我的功能出了什么问题(如果问题仅在于功能),如何使它正常工作? 我尝试在控制台中记录函数活动,但对于确切发生的事情仍然感到困惑。

我试图寻找: 如何通过CSShttp://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb 将JavaScript onclick事件设置为一个类,但无法正确应用这两种方法。

抱歉,如果不清楚或时间太长,这是我的第一篇文章。

真正的问题是您的临时img在触发onclick将始终包含最后一个图像,因为匿名函数(您用来处理onclick函数)不能实时捕获变量,而是在调用变量时捕获变量。

您可以在onclick事件中使用this关键字来获取当前图像:

window.onload = function() {
    var imgs = document.getElementsByTagName('img');
    for(var i = 0; i < imgs.length; i++) {
        var img = imgs[i];
        img.onclick = function() {
            newSrc = this.src; //this = reference to image that fired onclick
            focus = document.getElementById('focus');
            focus.src = newSrc; //no quotes for variable references!
        }
    }
}

希望这可以帮助!

您可以这样编码:

window.onload = function() {
    document.getElementsByTagName('img').forEach(function(){
        this.onclick = function() {
            document.getElementById('focus').src = this.src;
        }
    });
}

我认为代码很直观,但是请随时询问;)

暂无
暂无

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

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