本文主要是介绍js自定义实现类似锚点(内容部分滚动),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
场景:
效果图如上,类似锚点,但是屏幕不滚动。高度计算我不是很熟练。for循环写的比较麻烦。element plus 和Ant Design有类似组件效果。
html:
<template><div><div style="height: 400px;" class="header"></div><div class="contain"><div class="left"><button @click="oneClick(0)">111</button><button @click="oneClick(1)">222</button><button@click="oneClick(2)">333</button><button @click="oneClick(3)">444</button><button@click="oneClick(4)">555</button></div><div class="right"><div class="one item">100px</div><div class="two item">200px</div><div class="three item">300px</div><div class="four item">400px</div><div class="five item">500px</div></div></div><div class="footer"></div></div>
</template>
css:
<style>
.header {z-index: 999;position: relative;background: red;
}.footer {background: yellow;height: 400px;
}.contain {width: 80vw;position: relative;display: flex;
}.left {width: 200px;height: 300px;background: rgb(102, 214, 180);}.right {/* position: absolute; */left: 200px;
}.one {background: rgb(96, 96, 177);width: 400px;height: 100px;position: relative;z-index: 99;transition: all 0.3s ease;
}.two {background: rgb(218, 96, 207);height: 200px;transition: all 0.3s ease;
}.three {background: royalblue;height: 300px;transition: all 0.3s ease;
}.four {background: rgb(31, 151, 27);height: 400px;transition: all 0.3s ease;
}.five {background: rgb(233, 94, 52);height: 500px;transition: all 0.3s ease;
}
</style>
js:
<script>
export default {data() {return {height: 0,//需要偏移的高度nowIndex: 0,//现在选的indexchoosePre: 0,//上一次选的indexgoHeight: 0,//向上时已经滚动的高度containHeight: 0, //中间contain的高度}},methods: {oneClick(nowIndex) {let contain = document.getElementsByClassName('contain')[0]let items = document.getElementsByClassName('item');this.containHeight = 0//之前选的4 现在选的2for (let i = nowIndex; i < items.length; i++) {this.containHeight += items[i].offsetHeight}contain.style.height = this.containHeight + 'px'if (this.choosePre > nowIndex) {this.goHeight = 0for (let i = nowIndex; i < this.choosePre; i++) {this.goHeight += items[i].offsetHeight}this.height = Number(this.height) - Number(this.goHeight)for (let i = 0; i < items.length; i++) {if (nowIndex == 0) {items[i].style.transform = `translateY(0px)`;} else {items[i].style.transform = `translateY(-${this.height}px)`;}}this.choosePre = nowIndex}//之前选的2 现在选的3else if (this.choosePre < nowIndex) {this.height = 0for (let i = 0; i < nowIndex; i++) {this.height += items[i].offsetHeight}this.choosePre = nowIndexfor (let i = 0; i < items.length; i++) {if (nowIndex == 0) {items[i].style.transform = `translateY(0px)`;} else {items[i].style.transform = `translateY(-${this.height}px)`;}}}}}
}
</script>
这篇关于js自定义实现类似锚点(内容部分滚动)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!