Google places autocomplete, how to clean up pac-container?

后端 未结 5 1960
鱼传尺愫
鱼传尺愫 2021-02-12 13:41

I\'m using the google places autocomplete control, and it creates an element for the drop down with a class pac-container.

I\'m using the autocomplete in a

5条回答
  •  后悔当初
    2021-02-12 13:46

    I just encountered this issue as well. It may have something to do with my input field being inside of a flexbox but I haven't tried restructuring my page yet. Instead I added an onfocus listener to my input field as well as an onscroll listener to it's container. Inside I get the input field's position with getBoundingClientRect and then update my stylesheet with the values. I tried directly selecting and updating the .pac-container via document.querySelctor but that didn't seem to work. You may need a setTimeout to allow it to be added to the DOM first.

    Here is my code:

    let ruleIndex = null;
    const form = document.body.querySelector('.form');
    const input = document.body.querySelector('.form-input');
    
    const positionAutoComplete = () => {
      const { top, left, height } = inputField.getBoundingClientRect();
      if(ruleIndex) document.styleSheets[0].deleteRule(ruleIndex);
      ruleIndex = document.styleSheets[0].insertRule(`.pac-container { top: ${top + height}px !important; left: ${left}px !important; }`);
    }
    
    form.addEventListener('scroll', positionAutoComplete);
    input.addEventListener('focus', positionAutoComplete);
    

    As mentioned in an earlier answer, this breaks the minute google decides to rename .pac-container so not a perfect fix but works in the meantime.

提交回复
热议问题