2015-09-04 55 views
1

我的目标看起来很简单。当鼠标进入图像时,我希望图像的尺寸扩大并变为稍微不同的图像版本。当鼠标离开图像时,我希望它再次缩小并变回。我的代码没有完成这个,我不知道为什么。jQuery .html()不起作用

$(document).ready(function() { 
 
    $("#home").on("mouseenter", function() { 
 
    $("#home").animate({ 
 
     width: "10%", 
 
     left: "4%", 
 
     top: "0%" 
 
    }); 
 
    $("#home").html("<a href='home.php'><img src='image/home.png'></a>"); 
 

 
    /*It works fine up 'til here, but after this point I get no response 
 
    even clicking the link doesn't work. If I comment out the previous line of 
 
    code, everything works as expected (excepting of course that the HTML 
 
    doesn't change). It is quite confounding - the next bit of code is almost 
 
    a duplicate, and it gives me no trouble at all!*/ 
 

 
    }); 
 
    $("#home").on("mouseleave", function() { 
 
    $("#home").animate({ 
 
     width: "8%", 
 
     left: "5%", 
 
     top: "2%" 
 
    }); 
 
    $("#home").html("<a href='home.php'><img src='image/d.png'></a>"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<li id="home"> 
 
    <a href='home.php'> 
 
    <img src="image/d.png"> 
 
    </a> 
 
</li>

+2

只是出于好奇,为什么你在你找到时替换'li'的内容d只需更改'img'上的'src'? –

+1

如果您想更改图片来源,只需更改图片来源。我认为问题在于你用全新的DOM元素替换了id为“home”的元素的整个DOM子树。 (并且可能会在DOM树从它下面被替换时干扰动画) – dsh

+0

@PaulAbbott没有特别的理由,除了习惯。除非必须,否则我不急于做出改变。我已经有其他代码对列表项进行其他操作,需要进行更改,我必须返回并重新计算才能调整图像大小而不是其容器大小。如果这是最好的方法,我会做这些事情。 – Truth

回答

0

替换下面的行

$("#home").html("<a href='home.php'><img src='image/home.png'></a>"); 

//on mouseenter 
$("#home img").attr('src','image/home.png'); 

//and same for mouseleave 
$("#home img").attr('src','image/d.png'); 
+0

这个解决方案有效,但我仍然不明白为什么我以前的代码没有。为了我的教育而提供任何提示? – Truth

+0

您正在移除img标记并覆盖另一个,这就是为什么mousemove和moseleave事件也被删除 – alamnaryab

+0

更改图像源可能会导致转换滞后,除非您预先加载第二个图像。 –

0

如果我得到它的权利,你正在尝试做的,需要不同的方法。 在开始时加载两幅图像并悬停时隐藏第一幅图像。

使用CSS缩放图像也会更容易和更清晰。

请看:JSnippet Demo

HTML:

<div id='toggleImage'> 
    <img class='onMouseIn' src='dummy/250x250' /> 
    <img class='onMouseOut' src='dummy/250x250/png/d6e8ff' /> 
</div> 

CSS:

#toggleImage { 
    margin:0 auto; 
    display:inline-block; 
    position:relative; 
    width:250px; 
    height:250px; 
    transition-duration:300ms; 
    transition-property:transform; 
    transition-timing-function:ease; 
} 
#toggleImage img { 
    position:absolute; 
    top:0; 
    left:0; 
} 

JS(jQuery的):

$(function() { 
    $('#toggleImage').hover(
     function(){ 
      $(this).children('.onMouseOut').fadeOut(300); 
      $(this).css({'transform':'scale(1.2)'}); 
     }, 
     function(){ 
      $(this).children('.onMouseOut').fadeIn(300); 
      $(this).css({'transform':'scale(1)'}); 
     } 
    ); 
});