【问题标题】:JQuery fadeIn() not working despite correct log messages尽管日志消息正确,但 JQuery fadeIn() 无法正常工作
【发布时间】:2016-10-20 04:36:37
【问题描述】:

大家好!

我最近建立的主页有一个小问题。我尝试使用“内容”类淡入 HTML div,它会将两条日志消息都输出到控制台中,但它仍然没有淡入!

我当然删除了那些代码 sn-ps 中所有不需要的信息

这是我的 HTML

<div class="content">  </div>

还有我的 CSS

.content{
margin: 0px;
position: fixed;
display:none
background-image: url("../img/city_topdown_blurred.png");
background-size:cover;
width: 100%;
height: 100%;
}

最后是我的 jquery

$(document).ready(function(){
  console.log("fading in");
  $('.content').fadeIn("slow", function(){
    console.log("fading done");
  });
});

两条日志消息都会立即推送到我的浏览器 (Chrome) 即使时间设置为 10000 或更高。

【问题讨论】:

    标签: javascript jquery html css web


    【解决方案1】:

    display: none 重新添加后,您缺少; 似乎可以修复它,这是一个工作示例:https://jsfiddle.net/nbekm981/1

    缺少; 的原因是它设置了无效的display: none background-image: url("../img/city_topdown_blurred.png");。因为它是无效的,所以它使用默认的display: block;(它是自动可见的)。所以你的淡入在它开始之前就已经完成了。

    【讨论】:

    • 哦是的没看到
    【解决方案2】:

    display:none; 后面少了一个分号

    此外,图像(用于背景)可能需要一些时间来加载,因此您可能需要在淡入之前预加载图像。

    请参阅下面的运行演示

    $(document).ready(function() {
      // pre-load the image
      $('<img/>').attr('src', 'http://lorempixel.com/1024/1024').load(function() {
        console.log("image done loading");
        // prevent memory leaks
        $(this).remove();
    
        // assign image to .content 
        $('.content').css('background-image', 'url(http://lorempixel.com/1024/1024)');
    
        console.log("fading in starts");
        // fade in 
        $('.content').fadeIn(2000, function() {
          console.log("fading done");
        });
      });
    });
    .content {
      margin: 0;
      position: fixed;
      display: none;
      /*background-image: url("http://lorempixel.com/1024/1024");
        background-color: green;*/
      background-size: cover;
      width: 100%;
      height: 100%;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="content">
    </div>

    【讨论】:

      【解决方案3】:

      来自 jQuery 文档

      .fadeIn() 方法动画匹配元素的不透明度。它类似于 .fadeTo() 方法,但该方法不会取消隐藏元素并且可以指定最终的不透明度级别。

      我不相信它会使用display: none 进行动画处理,而是使用opacity: 0

      【讨论】:

      • “它类似于 .fadeTo() 方法,但该方法不会取消隐藏元素” - 该方法是 .fadeTo() - 而 .fadeIn() 方法确实“取消隐藏”元素所以它会改变它的display 属性......这就是我解释它的方式
      • 只是缺少分号
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多