对mousemove事件产生不必要的轻弹效果

时间:2018-10-30 11:50:53

标签: javascript html css

我有一个框架(父)和一个(孩子)内的矩形,我想根据鼠标位置在x轴上移动此矩形...每当我尝试移动此矩形时,我都会看到轻拂效果...有人可以指导我解决此问题吗?

 let frame = document.querySelector('.frame') ;
        let slider = document.querySelector('.frame .slider') ; 
        let mouseX = undefined ;
        frame.addEventListener('mousemove',function(e){
            mouseX = e.offsetX ;
            slider.style.left = mouseX + 'px' ;
        }) ;
 html,body{
            height: 100%;
        }
        body{
            padding: 0 ;
            margin: 0 ;
        }
        .frame{
            width: 75vw ;
            height: 75vh;
            border: 4px solid rgb(220,220,220) ;
            position: relative ;
            top: 50% ;
            left: 50%;
            transform: translate(-50%,-50%) ;
        }
        .frame .slider {
            position: absolute ;
            width: 1% ;
            height: 100%;
            left: 100% ;
            background-color: rgb(30,30,30) ;
            cursor: pointer;
        }
 
    <div class="frame">
        <div class="slider"></div>
    </div>

1 个答案:

答案 0 :(得分:2)

您需要使用mouseX = e.clientX ;而不是mouseX = e.offsetX ;,因为当鼠标移至滑块上并轻拂时,offsetX将重置,第二次希望会有所帮助:)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        html,body{
            height: 100%;
        }
        body{
            padding: 0 ;
            margin: 0 ;
        }
        .frame{
            width: 75vw ;
            height: 75vh;
            border: 4px solid rgb(220,220,220) ;
            position: relative ;
            top: 50% ;
            left: 50%;
            transform: translate(-50%,-50%) ;
        }
        .frame .slider {
            position: absolute ;
            width: 1% ;
            height: 100%;
            left: 100% ;
            background-color: rgb(30,30,30) ;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="frame">
        <div class="slider"></div>
    </div>
    <script>
        let frame = document.querySelector('.frame') ;
        let slider = document.querySelector('.frame .slider') ; 
        let mouseX = undefined ;
        frame.addEventListener('mousemove',function(e){ 
            mouseX = e.clientX ;
            slider.style.left = mouseX - frame.getBoundingClientRect().left + 'px';
            
        }) ;

    </script>
</body>
</html>