简体   繁体   中英

jQuery on('resize') not working as expected

I wrote some jQuery to dynamically position an element. While it works on load, it doesn't work when the window is resized.

The code I have:

  $(document).ready(function() {
      var offset = $("#kDropdown").offset();
      //$(".hidden-dropdown").css('position', 'absolute')
      //$(".hidden-dropdown").css('left', offset.left);
      $(document).on('resize', function () {
        $(".hidden-dropdown").css('position', 'absolute')
        $(".hidden-dropdown").css('left', offset.left);
      }).trigger('resize');
    });


      <div class="hidden-dropdown hide">
        <ul>
          <li><a href="#">Item One</a></li>
          <hr />
          <li><a href="#">Item Two</a></li>
          <hr />
          <li><a href="#">Item Three</a></li>
        </ul>
      </div>

Any ideas?

Usually, the one resized is the window , hence:

$(window).on("resize", function() {
    console.log("yay");
});

You can attach it with the resize method directly:

$(window).resize(function() {
    console.log("direct yay");
});

They are both the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM