2014-10-28 49 views
0

我想創建一些隱藏的選項,除非用戶在特定區域使用鼠標。讓我們舉個例子:Google+個人資料頁面:創建懸停可見按鈕

The normal state of the profile picture

當你與圖片上的鼠標光標去,會出現按鈕。

enter image description here

這裏是我的嘗試:

var $button = $("#button"); 
 

 
$("#profile-picture").on("mouseover", function() { 
 
    $button.show(); 
 
}).on("mouseout", function() { 
 
    $button.hide(); 
 
});
#profile-picture { 
 
    width: 150px; 
 
    height: 100px; 
 
} 
 
#button { 
 
    position: absolute; 
 
    display: none; 
 
    width: 30px; 
 
    height: 30px; 
 
    top: 45px; 
 
    left: 70px; 
 
    opacity: 0.75; 
 
    cursor: pointer; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<img src="http://datastore01.rediff.com/h450-w670/thumb/69586A645B6D2A2E3131/ckez1n08svw8f3en.D.0.Sidharth-Malhotra-Student-of-the-Year-Photo.jpg" id="profile-picture"> 
 
<img src="http://img3.wikia.nocookie.net/__cb20090227194712/java/images/0/0e/Camera_icon.gif" id="button" />

的問題是,當我將光標放在#button去,它閃爍。我能做什麼?

+0

你爲什麼做這與jQuery?您可以使用css :) – 2014-10-28 20:10:52

+0

,因爲當您將鼠標懸停在按鈕上時,會觸發按鈕上的鼠標懸停。 – vaso123 2014-10-28 20:10:55

+0

@BojanPetkovski,我需要在該按鈕上有'click()'事件。發佈你的想法,我不會downvote! – Victor 2014-10-28 20:11:55

回答

4

最簡單的方法是將它們放在同一個div中,然後使用mouseover/out爲該div。例如:http://jsfiddle.net/1g24mhhz/

HTML:

<div id="profile-picture"> 
    <img src="http://datastore01.rediff.com/h450-w670/thumb/69586A645B6D2A2E3131/ckez1n08svw8f3en.D.0.Sidharth-Malhotra-Student-of-the-Year-Photo.jpg" class="profile"> 
    <img src="http://img3.wikia.nocookie.net/__cb20090227194712/java/images/0/0e/Camera_icon.gif" id="button" /> 
</div> 

CSS編輯:

#profile-picture .profile { 
    width: 150px; 
    height: 100px; 
} 

編輯:你可能不應該使用一個ID爲DIV,因爲你可能有一個頁面上的多個配置文件。這只是用你已經使用過的代碼來展示它。

1

一個簡單的CSS方法。您可以在按鈕上有一個點擊事件:)

$('#button').on('click', function() { 
 
    alert('I am clickable'); 
 

 
});
#profile-picture, 
 
.hover-wrap { 
 
    width: 150px; 
 
    height: 100px; 
 
} 
 
#button { 
 
    position: absolute; 
 
    display: none; 
 
    width: 30px; 
 
    height: 30px; 
 
    top: 0px; 
 
    left: 0px; 
 
    bottom: 0; 
 
    right: 0; 
 
    margin: auto; 
 
    opacity: 0.75; 
 
    cursor: pointer; 
 
} 
 
.hover-wrap { 
 
    position: relative; 
 
} 
 
.hover-wrap:hover #button { 
 
    display: block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
 

 
<div class="hover-wrap"> 
 
    <img src="http://datastore01.rediff.com/h450-w670/thumb/69586A645B6D2A2E3131/ckez1n08svw8f3en.D.0.Sidharth-Malhotra-Student-of-the-Year-Photo.jpg" id="profile-picture"> 
 
    <img src="http://img3.wikia.nocookie.net/__cb20090227194712/java/images/0/0e/Camera_icon.gif" id="button" /> 
 
</div>

0

您可以使用CSS:懸停屬性來顯示/隱藏按鈕,沒有使用Javascript需要。

訣竅是兄弟選擇:

#profile-picture:hover + #button, #button:hover{ 
    display:block; 
} 

試試這個: http://jsfiddle.net/6s9200ab/