【问题标题】:jQuery-shake-on-clik on div - shakes no matter where i clickjQuery-shake-onclick on div - 无论我点击哪里都会震动
【发布时间】:2016-03-24 20:42:46
【问题描述】:

我正在尝试在单击 div ITSELF 时使<div> 抖动,但到目前为止,无论我在页面的哪个位置单击,所述<div> 都会抖动。

这是我的代码:

#port-two {
  color: white;
  background: black;
  height: 250px;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  resize: vertical;
  text-align: center;
  font-size: 35px !important;
  font-family: 'Exo', sans-serif !important;
  font-weight: 200 !important;
}
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<script>
  $(document).click(function() {
    $("#port-two").effect("shake");
  });
</script>

<div id="port-two" class="me">this is what's supposed to shake WHEN IT ITSELF IS CLICKED. It now shakes no matter where you click :(</div>

【问题讨论】:

    标签: jquery html shake


    【解决方案1】:

    这仅仅是因为您将事件处理程序附加到了document。要执行您需要的操作,您应该将其附加到 #port-two 元素。试试这个:

    #port-two {
      color: white;
      background: black;
      height: 250px;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      resize: vertical;
      text-align: center;
      font-size: 35px !important;
      font-family: 'Exo', sans-serif !important;
      font-weight: 200 !important;
    }
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    
    <script>
      $(function() {
        $('#port-two').click(function() {
          $(this).effect("shake");
        });
      });
    </script>
    
    <div id="port-two" class="me">It now shakes only when clicked :)</div>

    【讨论】:

    • 太棒了!我是一名在 FreeCodeCamp 完成该计划的新手。我已经为此苦苦挣扎了一两个小时了。我在某处阅读了文档附件是我需要做的事情,但我不记得为什么了。我想我最好再检查一下文档。
    • 没问题,很高兴为您提供帮助。关于文档,您需要在文档准备好时运行您的代码——这就是$(function() { }); 在我上面的代码中所做的事情。当您附加事件时,它们应该被放置在要引发该元素的元素上(或者如果事件在 DOM 中冒泡,则为父元素)
    【解决方案2】:

    您已将点击事件添加到“文档”而不是您的元素。 我还建议您封装任何相关的内容 使用 $(document).ready 到 DOM...

    $(document).ready(function() {
        $( "#port-two" ).click(function() {
            $(this).effect( "shake" );
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 2015-01-04
      • 2020-09-01
      • 2013-01-02
      • 2020-10-09
      相关资源
      最近更新 更多