jQuery toggleClass only works for a split second, then it reverts back to how it previously was

守給你的承諾、 提交于 2019-12-11 06:17:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!