Detect if dropdown navigation would go off screen and reposition it

后端 未结 3 1467
谎友^
谎友^ 2020-12-02 10:18

I\'ve got your typical dropdown navigation, and I\'m trying to make sure the drop menu links are always accessible and visible:

  • 3条回答
    •  旧时难觅i
      2020-12-02 10:32

      Here is a function that can be used for menus that fly-out to the right, or down (based off @r0m4n's code):

      function fixFlyout (containerElement, parentElement,flyoutElement,flyoutDirection) {
          $(parentElement).on('mouseenter mouseleave', function (e) {
              var element = $(flyoutElement, this);
              var offset = element .offset();
              switch(flyoutDirection) {
                  case 'down':
                      var top = offset.top;
                      var height = element.height();
                      var windowHeight = $(containerElement).height();
                      var isEntirelyVisible = (top + height <= windowHeight);
                      break;
                  case 'right':
                      var left = offset.left;
                      var width = element.width();
                      var windowWidth = $(containerElement).width();
                      var isEntirelyVisible = (top + width <= windowWidth);
                      break;
              }
              if (!isEntirelyVisible ) {
                  $(element).addClass('edge');
              } else {
                  $(element).removeClass('edge');
              }
          });
      }
      //Level 1 Flyout
      fixFlyout(containerElement = '.header',parentElement = '.header .navigation>.menu>.expanded',flyoutElement = '.menu:first',flyoutDirection = 'down');
      

    提交回复
    热议问题