简体   繁体   中英

Traversing the DOM in Angular 4 with jQuery

I need help in updating the CSS for selectedElement, currently, this works but only for the first element.

Basically, I have a link, when I click on it:

(click)="showUserDetails($event)"

I'm passing the x & y coordinates to my method and want to use this to update the css and enabled a boolean flag which shows the div:

  showUserDetails(el: any) {
let target = el.target || el.srcElement;
  let selectUsername = (document.getElementById('userDetailsInfo') as HTMLInputElement);
  selectUsername.style.top = target.offsetY + "px";
  selectUsername.style.left = target.offsetX + "px";
  this.selected = true;
  el.preventDefault();

}

Currently, the above code only seems to work for the first element and I'm trying to figure out a way to have it so based on the clicked element, go up the dom and find me the div with the id of 'userDetailsInfo' and apply the top/left values to that, and not just to the first item.

I actually solved it like so:

  private hostEl: HTMLElement;

  constructor(el: ElementRef) {
      this.hostEl = el.nativeElement;
  }

  ngOnInit() {
    window.addEventListener('scroll', this.scroll, true);
  }

  ngOnDestroy() {
      window.removeEventListener('scroll', this.scroll, true);
  }

  //Get the header
  let header = (document.querySelector('.header') as HTMLInputElement);

  if (window.pageYOffset >= 100){
      header.classList.add('sticky');
  } else {
      header.classList.remove('sticky');
  }

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