2014-09-30 68 views
0

我想要一個元素在添加'push'類時變得固定,然後當類'push'被移除時變成相對的。toggle class if else css

這是我有:

$("#menuToggle").click(function() { 
    $('.wrapper,header,nav').toggleClass('push', function() { 
     if ($('.wrapper,header,nav').hasClass('push')) { 
      $('.wrapper').css('position', 'fixed'); 
     } else { 
      $('.wrapper').css('position', 'relative'); 
     } 
    }); 
}); 

這裏是CSS:

.push { 
left:200px; 
position:fixed; 
} 
.wrapper { 
position:relative; 
float:left; 
top:0; 
width:100%; 
z-index:2; 
background:#fff; 
transition: all 1s ease; 
-webkit-transition: all 1s ease; 
-moz-transition: all 1s ease; 
} 
nav { 
position:fixed; 
line-height:50px; 
margin-left:-200px; 
z-index:0; 
width:200px; 
height:100%; 
float:left; 
color:#fff; 
background:#030e17; 
} 
header { 
position:fixed; 
z-index:10; 
float:left; 
width:100%; 
background:#fff; 
border-bottom:solid 1px #CCC; 
transition: all 1s ease; 
-webkit-transition: all 1s ease; 
-moz-transition: all 1s ease; 
} 

這是爲什麼不工作?

謝謝

+5

爲什麼不加'.push {位置是:固定; }'到你的樣式表,或者只是針對你的包裝:'.wrapper.push {position:fixed; }'? – Pete 2014-09-30 15:03:54

+0

不是沒有你的HTML – 2014-09-30 15:03:53

+2

['toggleClass'](http://api.jquery.com/toggleclass/)沒有這樣的過載。 – Stijn 2014-09-30 15:06:51

回答

0

我假設你不希望所有的元素成爲fixed,這樣你就不能添加到position: fixed CSS .push類的聲明。但是你可以讓更多的規則只.wrapper

.wrapper { 
    position: relative; 
} 
.wrapper.push { 
    position: fixed; 
} 

你JS將變爲:

$("#menuToggle").click(function() { 
    $('.wrapper, header, nav').toggleClass('push'); 
}); 
0

問題是你有在toggleclass函數。 (它並不需要這個)

嘗試:

$("#menuToggle").click(function() { 
    $('.wrapper,header,nav').toggleClass('push'); 

     if ($('.wrapper,header,nav').hasClass('push')) { 
      $('.wrapper').css('position', 'fixed'); 
     } else { 
      $('.wrapper').css('position', 'relative'); 
     } 

}); 

這裏的工作演示:(檢查元素);

http://jsfiddle.net/LuwLn962/

0

//撥動類的CSS

<!DOCTYPE html> 
<html> 
<head> 
<style> 
.left-panel{ 
height:200px; 
background:red; 
width:30px; 
float:left; 

} 
.div1{ 
background:#cecece; 
width:25%; 
height:300px; 
float:left; 
top:0; 
position:relative; 
} 
.div2{ 
background:#333333; 
width:68%; 
height:300px; 
float:left; 
top:0; 
position:relative; 
} 


</style> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $(".left-panel").click(function(){ 

if($(".div1").css("display")=="block") 
{ 

$(".div1").hide("slow"); 
$(".div2:visible").animate({ 

    width: "+=350px" 

}, "slow"); 

} 
else 
{ 

$(".div1").show("slow"); 
$(".div2:visible").animate({ 

    width: "-=350px" 

}, "slow"); 

} 

    }); 
}); 
</script> 
</head> 
<body> 
<div class="left-panel"></div><div class="div1"></div><div class="div2"></div> 

</body> 
</html>