我正在尝试学习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';
}
}
}
我的功能出现了什么问题(如果问题只是功能),我怎样才能使它工作?我尝试在控制台中记录功能活动,但我仍然对于究竟发生了什么感到困惑。
我尝试过:How do you set a JavaScript onclick event to a class with css和http://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_lightbulb,但无法正确应用其中任何一种方法。
如果不清楚或太长,请道歉,这是我的第一篇文章。
答案 0 :(得分:2)
真正的问题是你的临时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!
}
}
}
希望这有帮助!
答案 1 :(得分:1)
您可以这样编码:
window.onload = function() {
document.getElementsByTagName('img').forEach(function(){
this.onclick = function() {
document.getElementById('focus').src = this.src;
}
});
}
我认为代码很直观,但随意问;)