【问题标题】:I have a class that I am trying to toggle on but it is not working properly我有一门课,我想打开它,但它不能正常工作
【发布时间】:2014-10-07 13:00:50
【问题描述】:

当我单击一个按钮时,我试图将一个类切换到我的一个 div 上,由于某种原因,该类将被添加到 div 中,但实际的 CSS 属性不会发生。我正在尝试运行的功能位于底部。

这是我的代码:

HTML

<div class="mainPage">
   <form class="homeButton" action="">
      <input type="submit" value="Click to see who has had a worse day!">
   </form>
</div>
<div class="textBox">
   <h3>On (fill date), this person had a really terrible day.</h3>
   <div class="badEvent">
      <p>
      </p>
   </div>
   <button>Close</button>
</div>

CSS

.mainPage {
   background-color: #043D5D;
   color: white;
   text-align: center;
   position: relative;
   top: 0px;
   left: 0px;
   right: 0px;
   h2 {
      font-size: 4em;
   }
   p {
      font-size: 2em;
   }
   form {
      padding-bottom: 20px;
      input {
         width: 350px;
         height: 50px;
         border-radius: 10px;
         font-size: .95em;
         border: 1px solid #EB5055;
         background-color: #EB5055;
         cursor: pointer;
      }
   }
}


.replace {
   background-color: red;
}

JS

$(".homeButton").on("click", function(event){

   event.preventDefault();
   $(".textBox").toggleClass('.replace');

});

【问题讨论】:

  • 你能提供你的 html 标记吗?
  • 抱歉,我添加了一个发布问题的问题。现在应该有 html 标记 @bencripps。
  • 一方面,您需要将事件作为argument 添加到您的匿名函数中。

标签: javascript jquery css sass


【解决方案1】:

您的课程.homeButton 必须在您的按钮上,而不是在您的表单标签中。此外,如果您不发送表单,最好只使用不带表单的锚标记或按钮标记。

【讨论】:

    【解决方案2】:

    改成这样:

    $(".homeButton").on("click", function(event){ // add event inside the brackets
        event.preventDefault();
        $(".textBox").toggleClass('replace'); // remove the . from ('.replace')
    });
    

    .replace 更改为replace,因为您已经在切换课程。

    click 函数中添加一个event 参数,因为您使用的是event.preventDefault();

    JSFiddle Demo

    【讨论】:

      【解决方案3】:

      事情是这样的:

      $(".textBox").toggleClass('.replace');
      

      您实际上是在切换课程 .replace 而不是 replace. 仅用于查询过程。类名仍然是replace。所以,改成

      $(".textBox").toggleClass('replace');
      

      和代码will work

      【讨论】:

        【解决方案4】:

        这是整个样式表还是为了简洁而将其截断?如果它没有被切断,请检查 .replace 之后似乎缺少的最后一个括号,并从 toggleClass 中删除句点。

        $(".textBox").toggleClass('replace');
        

        【讨论】:

        • 我把它从一个较长的样式表中剪下来,并没有复制它。我现在已经更新了这个问题。感谢您了解这一点。
        • 该死的hjpotter92在编辑时击败了我,哈哈。
        猜你喜欢
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        • 2014-12-03
        • 2013-02-20
        • 2015-03-24
        • 2020-01-20
        • 1970-01-01
        • 2019-11-12
        相关资源
        最近更新 更多