2011-10-03 67 views
0
<section id="wheel_section"> 
<nav class="position"> 
    <a href="#" class="pos-1">LOC 1</a> 
</nav> 
<nav class="position"> 
    <a href="#" class="pos-2">LOC 2</a> 
</nav> 
<nav class="position"> 
    <a href="#" class="pos-3">LOC 3</a> 
</nav> 
<nav class="position"> 
    <a href="#" class="pos-4">LOC 4</a> 
</nav> 
<nav class="position"> 
    <a href="#" class="pos-5">LOC 5</a> 
</nav> 
</section> 
<section id="wheel_wheel"> 
<p> 
    <img id="the_wheel" src="position_1.gif" width="233" height="233" align="absmiddle" /> 
</p> 
</section> 

试图更改悬停时的图像(pos-1,pos-2等等)需要更改“the_wheel”中的图像。这些都是gif,而且id越高,gif的旋转速度越快。如果我将鼠标移动到左侧,那么ID就会变小,GIF的旋转速度会变慢,这就是它们的制作方式。将鼠标悬停在ID上更改图像

尝试这样:

$(document).ready(function(){ 
$("#wheel_section .position .pos-1").hover(function() { 
    $('img#the_wheel').attr("src", "position_1.gif"); 
}); 

$("#wheel_section .position .pos-2").hover(function() { 
    $('img#the_wheel').attr("src", "position_2.gif"); 
}); 

$("#wheel_section .position .pos-3").hover(function() { 
    $('img#the_wheel').attr("src", "position_3.gif"); 
}); 

$("#wheel_section .position .pos-4").hover(function() { 
    $('img#the_wheel').attr("src", "position_4.gif"); 
}); 

$("#wheel_section .position .pos-5").hover(function() { 
    $('img#the_wheel').attr("src", "position_5.gif"); 
}); 
}); 

,但我想有一个更好的aproach也..还是我错了? :)

+1

[会这样满足](http://jsfiddle.net/Shef/RCyV6/)? – Shef

+0

谢谢。我复制相同的代码在我的本地主机上,悬停将获得position_undefined.gif –

+0

你也必须改变标记,这就是为什么。 :) – Shef

回答

3

有两件事情:

  • 预紧您的图像
  • DRY(不要重复自己)
  • 使用jQuery集合的力量

var wheels = [], 
    wheelcount = 5; 

// Preload the images 
for(var i = 1; i <= wheelcount; i++) 
    wheels.push($('<img/>').attr('src', 'position_' + i +'.gif')); 

// Wire up the mouseenter event on each element 
$("#wheel_section>nav>a").mouseenter(function() { 
    var c = $(this).attr('class'); 
    var i = parseInt(c.substring(c.indexOf('-')+1)) - 1; 
    $('img#the_wheel').attr('src', wheels[i].attr('src')); 
}); 
+0

谢谢,几乎不错,只有我悬停在第一个链接上,它给了我第二个GIF和最后没有:) –

+0

也让我们说,如果我将鼠标悬停在第4个链接上,将加载图像,如果我移动将鼠标悬停在另一个链接上,同样加载的图片将保留 –

+0

对不起,错过了数组索引的错误。得到了修复。 – joshperry

1

你或许应该先缓存图像,然后进行修改:

$(document).ready(function(){ 
    // preload and cache images 
    var $pos1 = $('<img/>').attr('src', 'position_1.gif').attr('id', 'the_wheel'); 
    var $pos2 ... 
    ... 
    var $pos5 ... 

    $("#wheel_section .position .pos-1").hover(function() { 
     $('img#the_wheel').replaceWith($pos1); 
    }); 
    ... 
} 
+0

谢谢。由于某种原因,图像没有显示在悬停... –

+0

嗯,你能提供一个测试链接或jsfiddle - 可能有其他事情正在进行。 – swatkins

+0

你的建议很有用,谢谢。一个:) –