简体   繁体   中英

Slide element won't fit perfectly to the parent container after resizing the window

My problem here is whenever I resize the window, the slide element won't just fit properly to the parent (See my jsfiddle below to see, I can't explain it pretty well). So for my own solution, I tried updating the element width variable whenever I resize my window.

These are the variables I'm trying to use:

const trendingNewsSlide = document.getElementById("trending-news-container"); // This is the parent or the container of slides
var trendingNews = trendingNewsSlide.querySelectorAll(".trending_news"); // This is my element 
var trendingNewsWidth = trendingNews[0].offsetWidth; // This is the one to be updated (for my own solution)

I am making a draggable slider and it requires me to subtract the element's width from the parent's offsetLeft :

trendingNewsSlide.style.left = `${trendingNewsSlide.offsetLeft - trendingNewsWidth}px`;

but because I want it to be responsive, I used a vw unit for the element's width, therefore the element width will unavoidably vary depending on the user's screen size.

I then attempted to use the code below, which I thought would change the variable:

window.onresize = () => {
  trendingNewsWidth = trendingNews[0].offsetWidth;
}

but nothing seems to happen. I've thought of reloading the page on window resize, but it's pretty annoying and a very awful way of fixing the problem.

Maybe a pretty dumb idea to fix my code so I'm sorry

Any of you have an idea on how to do it? Here is my full code

Your code does update the variable. I tested it by resizing the window.

If you try console logging the variable on resize, you can see that the variable's value changes.

But if another variable's value depends on this one, you will have to change that variable's value manually again on resize.

var trendingNews = document.querySelectorAll(".trending_news")
var trendingNewsWidth = trendingNews[0].offsetWidth

window.onresize = () => {
   trendingNewsWidth = trendingNews[0].offsetWidth
   console.log(trendingNewsWidth)
}

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