当我将鼠标悬停在现有图像上时,我尝试在图像上淡入图像,而无需为每个图像重写相同的函数。
目前我有:
<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时,会得到name属性“hoverimage1”
- 然后,它会淡入 ID 为“hoverimage1”的元素,具体方法是执行 $('#hoverimage1").fadeIn(500);
但问题是 name 属性没有“#”,而且我不想写“name="#hoverimage1”,因为这会让 ID 感到困惑。现在我的函数执行 $('hoverimage1") .fadeIn(500);这不是正确的语法。
有人可以帮我解决这个问题吗?是否可以将“#”附加到“$(this.getAttribute())”或其他内容?
最佳答案
如果您想在前面加上#
,那么您只需连接字符串即可:
$('#' + this.name)
但如果可能的话,我会使用元素索引:
$('.image').mouseenter(function() {
$('.other_images').eq($(this).index()).stop().fadeIn(500);
}).mouseout(function() {
$('.other_images').eq($(this).index()).stop().fadeOut(500);
});
这样,您甚至不需要在父图像的 name
属性中写入其他图像的 id
。
关于javascript - 正确的语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15648945/