创建悬停可见按钮

时间:2014-10-28 20:07:21

标签: javascript jquery html

我正在尝试创建一些隐藏的选项,除非用户在特定区域中使用鼠标。我们举一个例子: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上时,它会闪烁。我该怎么办?

3 个答案:

答案 0 :(得分: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;
}

编辑:您可能不应该为div使用ID,因为您可能在页面上有多个配置文件。这只是用你已经使用的代码来显示它。

答案 1 :(得分:1)

简单的CSS方法。您可以在按钮上点击一下事件:)

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

});
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用CSS:悬停属性来显示/隐藏按钮,不需要Javascript。

诀窍是兄弟选择器:

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

试试这个: http://jsfiddle.net/6s9200ab/