关于div的jQuery-shake-on-clik - 无论我点击哪里都会震动

时间:2016-03-24 20:42:47

标签: jquery html shake

当点击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>

2 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
#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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您已将点击事件添加到&#34;文档&#34;而不是你的元素。 我还建议你封装任何相关的东西 使用$(document).ready ...

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