问题
So this is my first question ever on stackoverflow, sorry if I ask this poorly or have failed to find the answer elsewhere.
I am using a simple toggleClass jQuery function to add a class called .slide-out that gives the whole body a left: 30% value. If I manually add the class it works properly. But if I use the toggleClass function to add the class it slides the whole body over 30% just like I expected but immediately moves the body back to its normal position. It sort of flashes and appears 30% over and then flashes again and is back to where it was.
my js code is wrapped in a document ready function and I haven't found any syntax errors.
JS:
$( document ).ready(function() {
$("#main-menu-btn").click(function() {
$('body').toggleClass("slide-out");
});
});
SASS:
body
height: 100%
position: relative
left: 0
.slide-out
left: 30%
JADE:
doctype html
html(lang="en")
head
title jade
meta(charset="utf-8")
meta(name="viewport", content="width=device-width, initial-scale=1")
link(rel="shortcut icon", href="/assets/img/favicons/favicon.ico")
link(rel="stylesheet", href="/assets/css/main.css")
body(class="slide-out")
.logo
h1 Whole Life Sports
.main-menu
ul
li Home
li Stuff
li Things
.page-nav
nav
a(href="", id="main-menu-btn") Main Menu
a(href="") Home
a(href="") Kids Games
a(href="") Max Sport Camp
a(href="") The Big Think
script(src="/assets/js/jquery-2.1.1.min.js")
script(src="/assets/js/functions.js" type="text/javascript")
回答1:
Use:
$("#main-menu-btn").click(function(event) {
$('body').toggleClass("slide-out");
event.preventDefault();
});
Or return false
for the click event.
See: http://api.jquery.com/event.preventdefault/
来源:https://stackoverflow.com/questions/30089026/jquery-toggleclass-only-works-for-a-split-second-then-it-reverts-back-to-how-it