2015-09-04 66 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)'}); 
     } 
    ); 
});