React实现双滑块交叉滑动
程序员文章站
2022-07-24 23:24:38
本文实例为大家分享了react实现双滑块交叉滑动的具体代码,供大家参考,具体内容如下html代码: &l...
本文实例为大家分享了react实现双滑块交叉滑动的具体代码,供大家参考,具体内容如下
html代码:
<body> <div id="root"></div> </body>
script代码:
<script type="text/babel"> const root = document.queryselector('#root') class comp extends react.component { constructor(...args) { super(...args) } fn(ev) { // 获取鼠标点击的距离 this.pagex = ev.changedtouches[0].pagex - ev.target.offsetleft // 获取父级 this.parentwidth = ev.target.parentnode.offsetwidth - ev.target.offsetwidth // 获取父级 this.parent = ev.target.parentnode // 获取线条 this.line = this.parent.children[2] // 获取左边小球 this.oball = this.parent.children[0] // 右边小球 this.oballtwo = this.parent.children[1] document.ontouchmove = this.fnmove.bind(this) document.ontouchend = this.fnend } fnmove(ev) { // 盒子偏移量 this.x = ev.changedtouches[0].pagex - this.pagex // 判断偏移量不能大于父盒子的宽 if (this.x >= this.parentwidth) { this.x = this.parentwidth } // 判断不能小于0 if (this.x <= 0) { this.x = 0 } // 计算线条的宽 小球交互 计算绝对值就是线条的宽 this.linewidth = math.abs(this.oballtwo.offsetleft - this.oball.offsetleft) // 线条的宽度 this.line.style.width = this.linewidth + 'px' // 小球距离左边的距离 ev.target.style.left = this.x + 'px' // 判断右边小球的offsetleft减掉左边小球的offsetleft值 如果小于0就是 右边小球距离左边最近 取出它的offsetleft值就是线条距离左边的值 if(this.oballtwo.offsetleft-this.oball.offsetleft<0){ this.line.style.left=this.oballtwo.offsetleft+'px' }else{ this.line.style.left=this.oball.offsetleft+'px' } } fnend() { document.ontouchmove = null document.ontouchend = null } render() { return (<div classname='box'> <div classname='ball' ontouchstart={this.fn.bind(this)}></div> <div classname='ball ac' ontouchstart={this.fn.bind(this)}></div> <div classname='line'></div> <div classname='linet'></div> </div>) } } reactdom.render(<comp />, root) </script>
css样式:
<style> body { margin: 0; padding: 0; } .box { width: 500px; height: 40px; background: #999; position: relative; margin: auto; margin-top: 100px; } .ball { width: 40px; height: 40px; background: red; position: absolute; border-radius: 50%; z-index: 10; } .ball.ac { background: #0f0; right: 0; } .line { height: 5px; width: 500px; background: rgb(200, 110, 7); position: absolute; top: 50%; left: 0; transform: translate(0, -50%); z-index: 5; } .linet { height: 5px; width: 500px; background: #fff; position: absolute; top: 50%; left: 0; transform: translate(0, -50%); } </style>
第二种方式:点击链接查看第二种
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。