2

当我将鼠标悬停在现有图像上时,我试图淡入现有图像之上的图像,而不为每个图像重新编写相同的函数。

目前我有:

<script type="text/javascript">

    $(document).ready(function() {

        $('.image').mouseenter(function() {  //fade in hover image
            $(this.getAttribute("name")).fadeIn(500);
        });                         
        $('.hoverimage').mouseout(function() { //fade out hover image
            $(this).fadeOut(500);
        });

    });

</script>

...
...

<!--base images-->
<img src="image1.png" class="image" name="hoverimage1">
<img src="image2.png" class="image" name="hoverimage2">
<img src="image3.png" class="image" name="hoverimage3">

<!--image to appear when hovering over-->
<img src="image1_glow.png" class="hoverimage" id="hoverimage1">
<img src="image2_glow.png" class="hoverimage" id="hoverimage2">
<img src="image3_glow.png" class="hoverimage" id="hoverimage3">

假设 CSS 已经存在,因此悬停图像放置在基本图像的顶部。我的代码试图做的是:

  • 当鼠标进入“image1.png”的div时,会得到名称属性“hoverimage1”
  • 然后它通过执行 $('#hoverimage1").fadeIn(500); 淡入 ID 为“hoverimage1”的元素;

但问题是名称属性没有“#”,而且我不想写“name="#hoverimage1",因为这会使 ID 混淆。现在我的函数执行 $('hoverimage1").fadeIn( 500); 这不是正确的语法。

有人可以帮我弄这个吗?是否可以将“#”附加到“$(this.getAttribute())”或其他内容?

4

2 回答 2

3

如果要添加 a #,则可以连接字符串:

$('#' + this.name)

但如果可能的话,我会为此使用元素索引:

    $('.image').mouseenter(function() {
        $('.other_images').eq($(this).index()).stop().fadeIn(500);
    }).mouseout(function() {
        $('.other_images').eq($(this).index()).stop().fadeOut(500);
    });

这样,您甚至不需要在父图像id的属性中写入其他图像。name

于 2013-03-26T22:59:10.320 回答
2

由于属性是hoverimage1,脚本实际上是在寻找一个<hoverimage1>元素。您需要将 a 连接#到开头:$("#"+this.getAttribute("name"))

于 2013-03-26T22:59:32.740 回答