gpt4 book ai didi

javascript - 绑定(bind)样式使整个页面跳跃(滚动)

转载 作者:行者123 更新时间:2023-11-28 15:10:24 25 4
gpt4 key购买 nike

在我的 SPA 前端,我有 580 高度的 div,其中包含 9 个较小的 div(大约 190px 高度)。父 div 有 overflow: hidden 所以我一次只能看到 3 个元素。每 5 秒我就改变样式 - 我添加负 margin-top,所以看起来它们向上滚动,新的 3 来自向下。

<div class="most__popular"
v-for="n, i in articles" :key="n.id"
:style="{margin: sliderMargin[i]}">

-

data() {
return {
articles: [],
errors: [],
step: 0
}
},
mounted() {
setInterval(() => {
this.step = (this.step + 1) % 3;
}, 5000);
},
computed: {
sliderMargin() {
const thresholds = [0, 3, 6];

return this.articles.map((_, i) =>
`${(i > thresholds[this.step]) ? '10px' : '-190px'} 0 10px 0`
);
}
}

其中 articles 只是包含 9 条记录的硬编码数据 JSON。

它工作正常但是当我滚动页面时我只看到最后一个元素(这个 580 高度父 div 的底部)并且当它从第三步变为第一步(从 7,8,9 子 div 到 1,2, 3) 它向下滚动我的页面..

我不希望它影响整个页面,我该如何解决这个问题?


编辑

我添加 repository demo , 让它在你的机器上运行:

安装 GIT 和 NodeJS(如果你还没有,你可能无法帮助我)

  • 克隆/下载 git clone https://dopeCode@bitbucket.org/dopeCode/scrolling-issue.git
  • 在 bash/cmd cd path/where/you've/cloned 中选择这个元素
  • 在 bash/cmd 中运行 npm install
  • 在 bash/cmd 中运行 npm run dev
  • 在浏览器中访问 localhost:8080

稍微滚动一下页面,这样您只会看到显示的 3 个中的最后一个元素。

最佳答案

你正在滑动图片改变边距顶部,这不是一个好主意。边距并不总是像开发人员预期的那样。对于这种目的,最好使用相对定位。

我更改了您的相对定位代码,它运行良好。对您的 scrollElements.vue 文件进行以下更改。

sliderTop 添加到您的计算部分。

        sliderTop() {
const scrollStep = 3;
const itemHeight = 194;

return this.articles.map((_, i) =>
`${(i < this.step*scrollStep) ? (-i*itemHeight) : (-this.step*scrollStep*itemHeight)}px`
);
}

使用 sliderTopmost__popular 元素的部分设置样式

             :style="{top: sliderTop[i]}">

修复以下 CSS:

.most__popular {
margin: 10px 0;
transition: 1s top; /*Only top transition is required*/
position: relative; /*Added relative positioning*/
}
.most__popular__container {
overflow: hidden;
height: 572px; /*Fixed this height*/
}

关于javascript - 绑定(bind)样式使整个页面跳跃(滚动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48541399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com