【问题标题】:Add a fading effect to inside my JavaScript function在我的 JavaScript 函数中添加淡入淡出效果
【发布时间】:2012-11-23 22:57:50
【问题描述】:

我有一个 JavaScript 函数,可以通过更改源来在幻灯片中显示图像。我试图创建 smth 以包含一个淡入淡出效果,但我认为这是灾难性的。这是我的 JavaScript 函数。我不需要一个完整的答案,只是一些帮助我实现这一目标的提示。我是 JavaScript 的初学者,但我想学好它。如果有办法在没有 jQuery 的情况下做到这一点,那就太好了,或者直接在这个函数中包含 jQuery 将是最好的。

{       
    function nextImage() {

    if (currentImage < 5) {
        currentImage = currentImage + 1;
    } else {
        currentImage = 1;
    }

    document.getElementById('image').src = 'images/' + currentImage + '.jpg';

    }
}

当然,什么淡入淡出会适应相反的功能,但我认为这个例子可以帮助像我这样的新手。

【问题讨论】:

标签: javascript jquery image gallery slideshow


【解决方案1】:

使用 jquery 会变成这样:

function nextImage() {

   if (currentImage < 5) {
       currentImage = currentImage + 1;
   } else {
       currentImage = 1;
   }
   $("#image").fadeOut('fast', function() {
       $("#image").attr('src','images/' + currentImage + '.jpg');
       $("#image").fadeIn('fast');
   });
}

【讨论】:

  • 这太棒了!非常感谢!我现在了解如何编译这两个脚本。再次,非常感谢!
【解决方案2】:

我不认为这是一个愚蠢的问题,但无论出于何种原因,我自己的问题都被否决了,去想想吧! (结束咆哮)

您可以考虑如果您能够使用 CSS,那么您可以尝试使用 CSS3 淡化过渡。

如果你用 Javascript 来做,我可能会使用 jQuery 来做,因为这些功能已经存在,你所要做的就是使用 .show('slow') 和 .hide('slow')参数“慢”会自动为您制作动画。

http://api.jquery.com/show/

否则如果你想从头开始写,那你大概可以看看jQuery源码看看实际的动画效果是怎么做的。

【讨论】:

  • 感谢您的回答。我知道我可以在 CSS3 中做到这一点,但为了学习 javascript 并为了更好的后备,我使用了 jquery。但是,是的,您是对的,CSS3 在某些方面确实令人兴奋。
【解决方案3】:

您应该使用 JQuery,因为它们使效果变得非常容易:

http://api.jquery.com/category/effects/fading/

看看他们的例子和文档

这是一个例子:

示例: 示例:动画隐藏的 div 一个一个地淡入,在 600 毫秒内完成每个动画。

<!DOCTYPE html>
<html>
<head>
  <style>
    span { color:red; cursor:pointer; }
    div { margin:3px; width:80px; display:none;
      height:80px; float:left; }
      div#one { background:#f00; }
      div#two { background:#0f0; }
      div#three { background:#00f; }
    </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <span>Click here...</span>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script>
  $(document.body).click(function () {
    $("div:hidden:first").fadeIn("slow");
  });
</script>

关于如何开始使用 JQuery 的一些提示:

var a = $(document); //  <-- set the hole document to variable a
var b = $("#myid"); // <-- set the element that has id="myid" to variable b
var c = $(".myclass"); // <-- set the element(s) that has class="myclass" to variable c
var d = $("img"); // <-- set the img element(s) to variable d

使用 Chrome Web Inspector 或 Firebug 调试您的 JavaScript 代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多