首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >鼠标移动Jquery移动块

鼠标移动Jquery移动块
EN

Stack Overflow用户
提问于 2022-12-04 01:27:45
回答 1查看 14关注 0票数 0

我需要脚本,这将改变translateX的位置取决于鼠标位置在这个块内。https://www.peaktwo.com/work/:这是它在一个直播网站上的样子,不能达到这个效果。有人能在jQuery上帮上忙吗?

代码语言:javascript
复制
$('.work__main').on("mousemove" ,function(e){
            let center = $(window).width()/2;
            if ((center - event.pageX) > 0 ) {
                $('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
            } else {
                $('.work__main').css("transform" , "translateX(-"+ event.pageX/10 +"px)")
            }
    });

这是我的代码--但当我试图像那样构建它时,当我把鼠标放在中间时,它会从一边跳到另一边。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-12-04 01:30:51

要解决当鼠标位于屏幕中心时元素从一边跳到另一边的问题,您可以添加一个额外的检查,以确保translateX值不超过某个阈值。

下面是一个如何做到这一点的例子:

代码语言:javascript
复制
$('.work__main').on("mousemove" ,function(e){
  let center = $(window).width()/2;
  let translateX = -event.pageX / 10; // Calculate the translateX value based on the mouse position

  // Limit the translateX value so that it doesn't exceed a certain threshold
  if (translateX > 50) {
    translateX = 50;
  } else if (translateX < -50) {
    translateX = -50;
  }

  // Apply the translateX value to the element
  $('.work__main').css("transform" , "translateX(" + translateX + "px)")
});

这将确保当鼠标位于屏幕中央时,元素不会从一边跳到另一边。您可以根据自己的喜好调整阈值(在本例中为50)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74672210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档