问题
I want to use a Toggle-Event, but only when the window is wider than a certain size. The DIV should be visible all the time though. My solution kind of works, but the if-statement doesn't trigger anymore, once I resize the window.
Any hints? Here's the link: http://jsfiddle.net/mihaene/wMrjc/
回答1:
Ok, assuming that I have figured out your problem I just post my solution: http://jsfiddle.net/5bxLS/
var toggleOn = false;
var toggleState = 0;
function slideIn() {
toggleState = 1;
$("#slider").stop().animate({bottom: "-20px"}, 300);
};
function slideOut() {
toggleState = 0;
$("#slider").stop().animate({bottom: "-180px"}, 300) ;
};
function setToggle() {
if(!toggleOn) {
$('#slider').toggle(slideIn, slideOut);
toggleOn = true;
}
};
function clearToggle() {
if(toggleOn) {
if(toggleState === 1)
$('#slider').click();
$('#slider').off('click');
toggleOn = false;
}
};
function evalToggle() {
if ($(window).width() > 500)
setToggle();
else
clearToggle();
};
//Apparently this does not work in webkit based browsers...
/*$(window).resize(evalToggle);
evalToggle();*/
//But this works:
$(window).resize(evalToggle).resize();
In order to stop the toggling you will have to unbind the event (which is click event in this case). The click event is also the one that executes the toggling. I build my solution in a way that toggling can be enabled in the beginning (depending on the window size). Additionally I've made a smooth transition if the toggle state was set to on if the window is made smaller. Hope this was the one you were searching for!
来源:https://stackoverflow.com/questions/10514554/toggle-animation-only-above-certain-window-width