1.在vue中要获取event事件对象 在绑定事件时要利用$event作为参数传递。
<template>
<div id="imgBox">
<!-- 碎片 -->
<div id="slidImg">
<img src="https://5-2ebf-4838-9ece-bde9690e8134.png" alt="">
</div>
<!-- 大图 -->
<div id="img">
<img src="https:/2-399de2f59fca.png" alt="">
</div>
<!-- 滑块部分 -->
<div id="sliding">
<div class="bg"></div>
<span id="huakuai" @mousedown='mousedownFn($event)' @mousemove='mousemoveFn($event)' @mouseup='mouseupFn($event)'></span>
</div>
</div>
</template>
2.css的部分 我用的是sass书写样式,sass里变量要类似这样写 $move: var(--moveLeft, 0px);js要修改sass中的变量 就需要用到.style.setProperty('css变量名',新值),--moveLeft就是css变量名。
<script> import axios from 'axios' export default { data() { return { isMove:false }; }, methods:{ mousedownFn(e){ this.isMove = true; }, mousemoveFn(e){ const box = document.getElementById("imgBox"); const sliding = document.getElementById("sliding"); const huakuai = document.getElementById("huakuai"); const img=document.getElementById('img'); if (this.isMove) { const offsetLeft = sliding.getBoundingClientRect().left; const maxLeft = sliding.getBoundingClientRect().width; const btnWidth = huakuai.getBoundingClientRect().width; if (e.clientX > offsetLeft + btnWidth / 2) { if (e.clientX < offsetLeft + maxLeft - btnWidth / 2) { // greenWid box.style.setProperty( "--moveLeft", `${e.clientX - offsetLeft - btnWidth / 2}px` ); } } } }, mouseupFn(e){ // console.log("离开", e); this.isMove = false; } } }; </script>
<style lang='scss' scoped> #imgBox { $imgHeight: 300px; $slidW: 100%; $spanWd: 80px; $move: var(--moveLeft, 0px); height: 500px; 600px; padding: 10px; box-sizing: border-box; background-color: rgb(240, 230, 229); position: relative; img{ 100%; height: 100%; } #img { margin-left: 20%; auto; // height: 140px; // background-color: rgb(175, 99, 91); } #slidImg { position: absolute; auto; height: 61px; left: $move; top: 120px; // background-color: sandybrown; transition:all 0s ease; } #sliding { position: relative; margin-top: 30px; $slidW; height: 60px; border-radius: 6px; background-color: rgb(219, 219, 219); overflow: hidden; .bg{ position: absolute; height: 100%; $move; left: 0; top: 0; background-color: rgb(49, 185, 79); transition:all 0s ease; } span { display: inline-block; position: absolute; left: $move; height: 60px; $spanWd; border-radius: 5px; background-color: rgb(255, 255, 255); background-image: url('../assests/右双箭头.png'); background-size: 40px; background-repeat: no-repeat; background-position: center; transition:all 0s ease; } } } </style>