2016-11-23 60 views
1

我試圖在鼠標光標懸停在圖像上時激活圖片。我正在使用jQuery來完成此操作。我無法弄清楚爲什麼它不適用於我的代碼的當前狀態。提前道歉,我剛開始我的網頁開發工作。無法讓jQuery識別鼠標懸停在圖像上

謝謝!

HTML

<!DOCTYPE html> 
<html> 
    <head> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <link href="CSS/stylesheet_test.css" rel="stylesheet" type="text/css"> 
    <link rel="stylesheet" href="CSS/animate.css"> 
    <link href="https://fonts.googleapis.com/css?family=Work+Sans:500&amp;subset=latin-ext" rel="stylesheet"> 
    <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"> 
    <script type="text/javascript" src="scripts/jquery-3.1.1.min.js"></script> 
    <script type="text/javascript" src="scripts/test.js"></script> 
    <title>Daryl N.</title> 
    </head> 
    <body> 
    <div class="container"> 
     <div class="navbar"> 
     <div class="nav-text"><span id="home"><a href="index_test.html">Home</a></span><span id="archive">Archive</span></div> 
     </div> 
     <div id="first" class="background"> 
     <div class="align-vert"><img id="me-pic" src="./images/me.jpg" alt="A picture of me is suppose to be here" style="width:240px;height:240px;" class="me-border animated bounceIn"><span class="daryl animated bounceIn">Hi, I'm Daryl</span></div> 
     </div> 
     <div id="second" class="background"> 
     <p class="align-vert">This is my personal website</p> 
     </div> 
    </div> 
    </body> 
</html> 

jQuery的

$(document).mousemove(function() { 
    if($('#me-pic').is(':hover') 
    { 
     alert("Hello"); 
    } 
}); 

UPDATE

我的問題的根源來自於我的形象div的z索引設置爲-1 。改變這個解決了我的問題,以及改變腳本。

+0

不要將mousemove事件綁定到整個頁面。它非常低效。想想該方法將要運行多少次。有一種方法可以通過使用mousemove的事件參數來使您選擇的方法工作,但需要比較屬性。改爲使用'$(selector).hover()'方法。 – magreenberg

回答

3

嗯,我不知道,如果你的方法應該工作或沒有,但有一個更好的方式來處理這個問題,設計原來的目的是:

$(document).ready(function() { 
    $('#me-pic').hover(function() { 
    alert("Hello"); 
    }); 
}); 
+0

這仍然不起作用。我的CSS文件中可能會有問題嗎? – darylnak

+0

嘗試將它包裝在'$(document).ready(function(){...});'中,因爲您似乎正在將js文件加載到頁面的其餘部分之上,這會導致它等待頁面完成加載。編輯答案 – casraf

+0

我創建了一個測試頁面,可以確認這個作品!我的當前頁面必須有問題。謝謝,+1。 – darylnak

2

使用jQuery您可以直接將懸停事件上選擇,試試這個:

$(document).ready(function() { 
    $('#me-pic').hover(function(){ 
     alert("Hello"); 
    }) 
}); 
+0

這仍然不起作用。我的CSS文件中可能會有問題嗎? – darylnak

+0

不太可能,您在控制檯中遇到什麼錯誤? – MCMXCII

1

解決的辦法是用hover jquery方法。

$('#me-pic').hover(function(){ 
    alert("Hello"); 
}) 

查看參考here

此外,我建議您刪除$(document).mousemove()事件。在這種情況下,這是效率低下的方法。