繁体   English   中英

如何在div鼠标悬停时显示按钮

[英]How to show button on div mouse hover

我想在 div 悬停时显示按钮。 当我将鼠标悬停在 div 上时,按钮显示否则隐藏。

我在divbutton div 中的按钮。

html

<div class="divbutton">
   <button type="button" style="display: none;">Hello</button>
</div>

当我将鼠标悬停在 div 上时,它应该显示,但我不知道该怎么做。 当我再次删除鼠标按钮时隐藏。 谢谢。

使用下面的选择器

button {
  display: none; /* Hide button */
}

.divbutton:hover button {
   display: block; /* On :hover of div show button */
}

演示

还要确保为div元素分配一些heightmin-height ,否则它将为0因为它不包含任何内容。 另外,不要使用display: none; 作为内联样式,因为内联样式具有最高的特异性,因此,您将被迫使用!important ,这是不好的。

在上面的示例中,我使用了button {/*Styles*/}但这是一个通用的元素选择器,因此请确保为button元素定义一个class

使用以下 jQuery 来执行您的任务。

这是一个jsfiddle演示

$(document).ready(function () {
    $(document).on('mouseenter', '.divbutton', function () {
        $(this).find(":button").show();
    }).on('mouseleave', '.divbutton', function () {
        $(this).find(":button").hide();
    });
});

Alien 先生的回答提供了一个很好的 CSS 实现。 如果你需要在 jquery 中,使用这个 -

$( ".divbutton" )
 .on("mouseenter", function() {
  $("button").show();
})
.on("mouseleave", function() {
  $("button").hide();
});

在纯 JavaScript 中 -

var buttonDiv = document.getElementsByClassName("divbutton")[0];  //better use some id and then use getElementById

buttonDiv.onmouseover = function() {
    document.getElementById("YourButtonId").style.display = 'block';
}

buttonDiv.onmouseout = function() {
    document.getElementById("YourButtonId").style.display = 'none';
}

试试这个:

$('.divbutton').mouseover(function(event)
{
   $(this).find('button').show();
});

$('.divbutton').mouseout(function(event)
{
   $(this).find('button').hide();
});

首先隐藏具有转换属性的按钮。

button{
transform:translate(100%,100%)
//this will move the button right and buttom
}

然后当你悬停在 div 上时,你把它带回来

.divbutton:hover button{
     //class name should have been divButton
     transform:translate(0,0)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM