用链接改变单独div的类

时间:2012-05-22 17:26:30

标签: jquery css jquery-animate

我需要先在页面加载时将.light课程添加到#banner,然后点击#change时,我想从.light淡化课程到.dark

<style type="text/css>
  #banner { width: 1000px; height: 500px; }
  .light { background: url(light.jpg) #ffffff; }
  .dark { background: url(dark.jpg) #000000; }
</style>

<script type="text/javascript">
  // no idea what to do
</script>

<div id="banner">
  stuff
</div>

<div id="container">
  <div id="leftCol">
    <a href="#" id="change">Change</a>
  </div>
</div>

4 个答案:

答案 0 :(得分:2)

解决。

现场演示: http://jsfiddle.net/oscarj24/Yh7pE/9/

$(function(){
  $("#banner").addClass("light");
  $("#change").on("click", function(e){
    $("#banner").toggleClass("light").hide().toggleClass("dark").fadeIn();
    e.preventDefault();
  });
});​

CSS:

  .light { 
        background: url(http://oursaviorschurch.com/img/bg_banner.jpg) #ffffff; 
        opacity: 0.30; /* FX, Safari, GC, Opera, decent browsers */
        -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=30)"; /* IE8 */
        filter: alpha(opacity=30); /* IE */
        /* in Safari, FX and Chrome add a fade transition */
        -webkit-transition: opacity .25s linear .1s;
        transition: opacity .25s linear .1s;  
    }

    .dark { 
        background: url(http://oursaviorschurch.com/img/bg_banner_dark.jpg) #000000;  
        opacity: 1; /* FX, Safari, GC, Opera, decent browsers */
        -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"; /* IE8 */
        filter: alpha(opacity=100); /* IE */
    }​

答案 1 :(得分:1)

$(function() {
  $('#banner').addClass('light');
  $('a#change').on('click', function(e) {
    e.preventDefault();
    $('#banner').removeClass('light').addClass('dark');
  });
})

答案 2 :(得分:0)

对于褪色,您需要在<head>中引用jQuery UI

<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.20/jquery-ui.min.js">
</script>

然后其余的:

// Wait until the document is ready before proceeding
$(function(){

  // Cache a reference to the banner to jQuery doesn't have to find it again
  var $banner = $("#banner");    

  // Immediately add the 'light' class
  $banner.addClass("light");

  // When #change is clicked, swap the classes on #banner
  $("#change").on("click", function(e){

    // Prevent the link from changing the page
    e.preventDefault();

    // Remove 'light', and add 'dark'
    $banner.addClass("dark", 1000).removeClass("light");

  });

});​

答案 3 :(得分:0)

您想要为类添加动画效果。对?这是一个带有现场演示的简单代码

$(document).ready(function(){
  $("#banner").addClass("light");
  $("#change").click(function(){
    $("#banner").stop(0,0).addClass("dark",800).removeClass("light",800);   
  });
});

这里有一个工作示例 http://jsfiddle.net/8nrzh/