通过ID在悬停时更改图像

时间:2011-10-03 19:56:04

标签: jquery css

<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会慢慢旋转,这就是它们的制作方式。

试过这个:

$(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");
});
});

但我想还有一个更好的方法..或者我错了? :)

2 个答案:

答案 0 :(得分:3)

一些事情:

  • 预装图片
  • 干(不要重复自己)
  • 使用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'));
});

答案 1 :(得分: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);
    });
    ...
}