最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery effect .fadeTo() with toggle? - Stack Overflow

programmeradmin6浏览0评论

I want to know the simplest way to toggle the .fadeTo() effect when someone click again on Click Me! button then it will reverse the process again. I mean just like the .fadeToggle() works or something like that. But using .fadeToggle() cause the div to disappear.

Here is my - JSFiddle

HTML

<button>Click Me!</button>
<div></div>

CSS

div {
    background-color: #ff0000;
    width: 200px;
    height: 200px;
    margin: 20px
}

jQuery

$(document).ready(function(){
  $("button").click(function(){
  $("div").fadeTo(400,0.4);
  });
});

I want to know the simplest way to toggle the .fadeTo() effect when someone click again on Click Me! button then it will reverse the process again. I mean just like the .fadeToggle() works or something like that. But using .fadeToggle() cause the div to disappear.

Here is my - JSFiddle

HTML

<button>Click Me!</button>
<div></div>

CSS

div {
    background-color: #ff0000;
    width: 200px;
    height: 200px;
    margin: 20px
}

jQuery

$(document).ready(function(){
  $("button").click(function(){
  $("div").fadeTo(400,0.4);
  });
});
Share Improve this question asked Apr 23, 2014 at 13:33 AnonymousAnonymous 10.2k3 gold badges26 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

You could use following snippet:

DEMO

$(document).ready(function () {
    $("button").click(function () {
        this.toggle = !this.toggle;
        $("div").stop().fadeTo(400, this.toggle ? 0.4 : 1);
    });
});

Or usually better solution is to toggle a class instead:

DEMO

CSS:

div {
    background-color: #ff0000;
    width: 200px;
    height: 200px;
    margin: 20px;
    -webkit-transition: opacity 400ms linear;
    transition: opacity 400ms linear;    
}

div.faded {
    opacity:.4;
}

jQuery:

$(document).ready(function () {
    $("button").click(function () {
        $("div").toggleClass('faded');
    });
});

Much simpler ,

 <button>fadeToggle p1</button>
 <p>This paragraph has a slow, linear fade.</p>
  <script>
   $( "button:first" ).click(function() {
     $( "p:first" ).fadeToggle( "slow", "linear" );
   });
 </script>
发布评论

评论列表(0)

  1. 暂无评论