Fix bug TS2339 - Property method does not exist on 'HTMLElement'
P粉481815897
P粉481815897 2023-12-25 22:52:23
0
1
609

When I press the "Next" button, the code below is triggered, performing the desired action (scrolling to my element if needed).

But I get this error: Error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'HTMLElement'. I cannot build my project.

const h3Title = ref<HTMLElement | null>(null)
function nextStep(
  currentStep.value++;
  
  if (h3Title.value) {
    h3Title.value.scrollIntoViewIfNeeded({behavior: "smooth", block: "start"})
  }

P粉481815897
P粉481815897

reply all(1)
P粉958986070

I think h3Title.value.scrollIntoView({block: "nearest"}) Using the standard scrollIntoView property will achieve what you want (no scrolling if the element is already in view).

If you really want typescript to recognize the non-standard scrollIntoViewIfNeeded property, you can add it to the HTMLElement interface (or create a new interface that extends HTMLElement):

// global.d.ts
interface HTMLElement {
  scrollIntoViewIfNeeded?: any;
}

Or: Convert h3Title.value to any type

(h3Title.value as any).scrollIntoViewIfNeeded()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!