我要做的是让访问者通过点击一组缩略图来更改图像。但是,我遇到的问题是我真的想摆脱将图像位置硬编码到脚本中的问题。我希望脚本足够便携,只要所使用的ID匹配,就可以在任何旧页面和图像集上运行。有没有办法可以改变以下内容来替换X的src代替A,B或C的src?
function clickSwitch() {
var element = document.getElementById("bigscreen");
element.setAttribute("src", "/img/projects/jamison/j2.jpg");
}
<img class="project-img" src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" id="bigscreen" />
<ul class="project-thumbnails">
<li><a href="#n" onclick="clickSwitch();"><img src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" /></a></li>
<li><a href="#n" onclick="clickSwitch();"><img src="/img/projects/jamison/j2.jpg" alt="Jamison: View Two" /></a></li>
</ul>
答案 0 :(得分:0)
我会把元素加载到一个数组中,在inlin html之外为每个元素添加一个事件,等等等等等等......但是你走了:
将“this”添加到您的onclick事件中,该事件将标记传递给clickSwitch。从那里你可以得到你需要的bigscreen。
<强> HTML 强>
<a href="#n" onclick="clickSwitch(this);"><img src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" /></a>
<强>的javascript 强>
function clickSwitch(el){
var src = el.firstChild.getAttribute('src');
var bigscreen = document.getElementById("bigscreen");
bigscreen.setAttribute("src", src);
}
答案 1 :(得分:0)
对于优雅降级的解决方案,我建议将大图像的图像源作为锚点的超级引用,因此如果javascript不存在,用户将被重定向到适当的全尺寸图像(例如{ {3}}):
<a class="thumbLinks" href="/img/projects/jamison/j1-BIG.jpg"><img src="/img/projects/jamison/j1-SMALL.jpg" alt="Jamison: View One" /></a>
$(document).ready(function() {
$('a.thumbLinks').click(function() {
//set the source of the big screen to the href of the clicked anchor
//throw in some animation too
$('#bigscreen').fadeOut("fast").
.attr('src', $(this).attr('href'))
.fadeIn();
//prevent link from being followed if Javascript is present
return false;
}
});
这种方法的优点:
答案 2 :(得分:-1)
为缩略图指定ID并将其发送到函数参数...
function clickSwitch(thumbClicked) {
var imgSrc = document.getElementById(thumbClicked).src;
var element = document.getElementById("bigscreen");
element.setAttribute("src", imgSrc);
}
HTML:
<img class="project-img" src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" id="bigscreen" />
<ul class="project-thumbnails">
<li><a href="#n" onclick="clickSwitch(thumb1);"><img src="/img/projects/jamison/j1.jpg" alt="Jamison: View One" id = "thumb1" /></a></li>
<li><a href="#n" onclick="clickSwitch(thumb2);"><img src="/img/projects/jamison/j2.jpg" alt="Jamison: View Two" id = "thumb2"/></a></li>
</ul>