我有一个页面上有一个很大的图像与许多缩略图。当您将鼠标悬停在缩略图上时,主图像将变为您刚刚将鼠标滚动到其上的图像。问题是我的缩略图越多,重复的代码就越多。我怎么能减少它呢?
Jquery代码如下所示。
<script type="text/javascript">
$('#thumb1')
.mouseover(function(){
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', '0001.jpg');
$('#big_img').fadeIn('slow');
});
});
$('#thumb2')
.mouseover(function(){
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', 'p_0002.jpg');
$('#big_img').fadeIn('slow');
});
});
$('#thumb3')
.mouseover(function(){
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', '_img/p_0003.jpg');
$('#big_img').fadeIn('slow');
});
});
$('#thumb4')
.mouseover(function(){
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', '0004.jpg');
$('#big_img').fadeIn('slow');
});
});
</script>
#big_img
=全尺寸镜像的ID
#thumb1
,#thumb2
,#thumb3
,#thumb4
=缩略图的ID
页面的主要代码是PHP,如果有帮助的话。
发布于 2010-04-02 21:30:22
首先,你应该修改你的代码,使每个缩略图都有一个容易找到的“类”。
假设你有
<img id="thumb1" scr=""/>
<img id="thumb2" scr=""/>
..
您的html应该如下所示
<img id="thumb1" class='thumb' scr=""/>
<img id="thumb2" class='thumb' scr=""/>
..
其次,你应该确保你所有的缩略图和它们的大图像之间有一个可识别的模式。在你的代码中,我们有
0001.jpg
p_0002.jpg
_img/p_0003.jpg
0004.jpg
您的文件所在的组织是什么?
现在让我们假设缩略图与bug图像具有相同的src
jQuery代码将缩减为:
$('.thumb').mouseover(function(){
var thumb_src = $(this).attr('src');
// ==> add code here to transform thumb_src into the big_img src
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', thumb_src);
$('#big_img').fadeIn('slow');
});
});
这段代码应该可以工作,只需等待将拇指的src转换为大图像的src的算法。
我希望这能帮助你杰罗姆·瓦格纳
发布于 2010-04-02 21:26:02
$(this)
是你的朋友。您还需要开发某种命名法,以便将您的文件名和id相匹配。我通常要做的是使用PHP生成HTML,但要放入处理文件名的特殊属性:
// PHP GeneratedContent
<?php
while(/* some range */) {
$i = 1;
$output .= '<element class="thumb" rel="p_' . $i . '.jpg">';
$i++;
}
echo $output;
?>
然后我将开始下一步:
$('.thumb').mouseover( function() {
var link = $(this).attr('rel');
/* Now that you have the link, just put it into whatever function you need to */
});
Fehays方法肯定是有效的,但通过这种方式,您不会有大量不必要的ID,也不需要进行不必要的参数传递。它将使用类thumb
自动传播到DOM中的每个实例。
发布于 2010-04-02 21:20:34
我想你可以只写一个函数。
applyImageFade('#thumb1','0001.jpg');
applyImageFade('#thumb2','p_0002.jpg');
//etc...
function applyImageFade(thumbId, image) {
$(thumbId).mouseover(function(){
$('#big_img').fadeOut('slow', function(){
$('#big_img').attr('src', image);
$('#big_img').fadeIn('slow');
});
});
}
https://stackoverflow.com/questions/2569238
复制