在悬停Jquery

时间:2019-01-17 09:56:37

标签: javascript jquery html css css3

我正在尝试进行更改以使悬停时的图片发生变化。这是我到目前为止所做的:

HTML

<div class="picture">
          <div class="text">
              <h1>Hey everyone!</h1>
          </div>

      </div>

CSS

.picture{
width: 200px;
height: 200px;
background-image: url("https://www.w3schools.com/css/trolltunga.jpg");}.text{
background-color: rgba(255,0,0,0.8);
width:200px;
height: 200px;
display: none;}

javascript

$(".picture").hover(function(){
$(this).children(".text").fadeToggle();});

2 个答案:

答案 0 :(得分:1)

如您在本例中所见,它工作正常:

$(".picture").hover(function() {
  $(this).children(".text").fadeToggle();
});
.picture {
  width: 200px;
  height: 200px;
  background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}

.text {
  background-color: rgba(255, 0, 0, 0.8);
  width: 200px;
  height: 200px;
  display: none;
}
<div class="picture">
  <div class="text">
    <h1>Hey everyone!</h1>
  </div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>

答案 1 :(得分:1)

jQuery(更改背景/显示文字):

HTML:

<div class="picture">
    <div class="text">
        <h1>Hey everyone!</h1>
    </div>
</div>

CSS:

.picture {
    width: 200px;
    height: 200px;
    background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}

.text {
    background-color: rgba(255, 0, 0, 0.4);
    width: 200px;
    height: 200px;
    display: none;
}

JS:

$(".picture").hover(function() {

    $(this).animate({
        opacity: 0.7
    }, 100, function() {
        $(this).css("background-image", "url('https://upload.wikimedia.org/wikipedia/en/2/27/Bliss_%28Windows_XP%29.png')");
    });

    $(".text").fadeToggle();
}, function() {

    $(this).animate({
        opacity: 0.7
    }, 100, function() {
        $(this).css("background-image", "url('https://www.w3schools.com/css/trolltunga.jpg')");
    });

    $(".text").fadeToggle();
});


https://jsfiddle.net/wlecki/28vschr1/

仅CSS解决方案:

HTML:

<div class="picture">
  <div class="text">
    <h1>Hey everyone!</h1>
  </div>
</div>

CSS:

.picture {
  width: 200px;
  height: 200px;
  background-image: url("https://www.w3schools.com/css/trolltunga.jpg");
}

.text {
  background-color: rgba(255, 0, 0, 0.4);
  width: 200px;
  height: 200px;
  opacity: 0;
}

.picture:hover {
  background-image: url("https://upload.wikimedia.org/wikipedia/en/2/27/Bliss_%28Windows_XP%29.png");
}

.picture:hover .text {
  opacity: 1;
}

https://jsfiddle.net/wlecki/9vnokdec/