Click happening on wrong element

时间:2019-04-16 23:24:41

标签: html css

I'm using the flex box justify-content setting to automatically put space between my elements on a header bar. It works really well. However, now, I've started toying around with an expanding search bar (i.e. it gets wider when the user focuses on it). This isn't a crucial part of the website, so I can easily forgo it. However, while playing around I noticed a weird behaviour happening with the button click.

If you run the fiddle below, you'll see that when you click the button without first selecting the input that the browser thinks you've clicked on the parent div. If you click again however, you'll have clicked on the actual button.

Can anyone explain why this is happening?

Also, maybe it is due to the CSS transformation, however that is there so that the div grows to the right rather than left (which is what happens when the justify-content is set to flex-end.

$(document).on("click", function(e) {
  alert('you clicked on ' + $(e.target).prop("tagName") + '.' + $(e.target).attr("class"));

});
.header-search {
  width: 4rem;
}

ul>li {
  display: inline-block;
  padding-left: 1rem;
  list-style-type: none;
}

.header-search:focus {
  width: 7rem;
}

.header-search-bar:focus-within {
  margin-left: -3rem;
  transform: translateX(3rem);
}

.container {
  margin-top: 25px;
  width: 75%;
  display: flex;
  align-items: stretch;
  flex-wrap: wrap;
  justify-content: space-between;
}

.left,
.right {
  display: flex;
  align-items: center;
}

.right {
  justify-content: flex-end;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="left">
    LEFT CONTENT

  </div>
  <div class="right">

    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li class="header-search-bar">

        <div class="parentDIV">
          <input type="search" class="header-search" placeholder="Search..." name="q" value="">
          <button type="submit" class="submitBTN" id="searchSubmit">SUBMIT
  </button>
        </div>


      </li>
    </ul>

  </div>
</div>

1 个答案:

答案 0 :(得分:0)

Rowan Baker-French在评论中正确指出,这与Prevent firing focus event when click on div.的重复

解决方法:

public function edit(User $user, RequestStack $request)
{
    $em = $this->getDoctrine()->getManager();
    $form = $this->createForm( UserType::class, $user);

    $form->handleRequest($request->getCurrentRequest());

    if ($form->isSubmitted() && $form->isValid()){

        $em->persist( $user);
        $em->flush();

        $this->addFlash('success', 'User updated.');
        return $this->redirectToRoute('user_index');
    }

    return $this->render('user/update.html.twig', [
        'form' => $form->createView(),
        'deleteForm' => $this->createDeleteForm($user)->createView()
    ]);

}