【问题标题】:jQuery: Fade in image while mouse over, fade out when mouse outjQuery:鼠标悬停时淡入图像,鼠标移出时淡出
【发布时间】:2018-03-26 09:39:46
【问题描述】:

这应该很简单。就是做不好。我希望我的网页加载不透明度为 50% 的图像。然后,在鼠标悬停时将不透明度提高到 1,并在鼠标移出时再次降低到 0.5。

<!DOCTYPE html>
<html lang='no'>
<meta charset ="utf-8"
<head>

<title>Øving 7</title>

<style type="text/css">
img {
  opacity: 0.5;
}
</style>

<script src="jquery-3.2.1.min.js"></script>

<script>

$(document).ready(function() {

    $("images").hover(function() {
        $(this).animate({opacity: 1.0}, 500);
    }, function() {
        $(this).animate({opacity: 0.5}, 500);
    });
    });

</script>

</head>

<body bgcolor="lightgrey">
<h1>Oppgave 1 - jQuery</h1>

<img class="bild" src="b1.jpg" alt="Bilde1" border="0"/>
<img class="bild" src="b2.jpg" alt="Bilde2" border="0"/>
<img class="bild" src="b3.jpg" alt="Bilde3" border="0"/>
<img class="bild" src="b4.jpg" alt="Bilde4" border="0"/>
<img class="bild" src="b5.jpg" alt="Bilde5" border="0"/>


</body>
</html>

【问题讨论】:

  • 为什么你认为$("images") 会选择img 元素?
  • $("images") 它应该是 $("img"),但是使用它来代替 $(".bild")。一个简单的 CSS 将解决您的问题。 .bild { 不透明度:.5; } .bild:hover { 不透明度:1; } 你可以根据需要添加过渡。

标签: jquery jquery-animate opacity


【解决方案1】:

只需将$("images") 更改为$("img") 或上课$(".build")

$("img").hover(function() {
    $(this).animate({opacity: 1.0}, 500);
}, function() {
    $(this).animate({opacity: 0.5}, 500);
});

【讨论】:

    【解决方案2】:
    Try this 
    

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
    
    $(document).ready(function() {
    
        $(".vs").hover(function() {
            $(this).animate({opacity: 1.0}, 500);
        }, function() {
            $(this).animate({opacity: 0.5}, 500);
        });
        });
    
    </script>
    <style>
    .vs{
     opacity: 0.5;
    width:33.33%;
    }
    </style>
    <div class="w3-row-padding w3-hide-small" style="margin:0 -16px">
    <div class="w3-third w3-center">
    <img src="https://www.w3schools.com/css/img_forest.jpg" class="vs">
    
    </div>
    
    <div class="w3-third w3-center">
    <img src="https://www.w3schools.com/css/img_forest.jpg" class="vs">
    
    </div>
    
    <div class="w3-third w3-center">
    <img src="https://www.w3schools.com/css/img_forest.jpg" class="vs">
    
    </div>
    
    </div>

    【讨论】:

      【解决方案3】:

      使用 CSS 而不是 jQuery。

      .bild {
         opacity: 0.5;
         transition: opacity .25s ease-in-out;
         -moz-transition: opacity .25s ease-in-out;
         -webkit-transition: opacity .25s ease-in-out;
         }
      
         .bild:hover {
            opacity: 1;
            }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 2011-07-05
        • 1970-01-01
        相关资源
        最近更新 更多