【问题标题】:Equation for image mouseover pan?图像鼠标悬停平移方程?
【发布时间】:2014-10-08 23:16:18
【问题描述】:

我有一个简单的 jQ 脚本:

  1. 设置宽度/高度的容器
  2. 风景图片(可以更大或 小于容器)
  3. 当用户将鼠标悬停在图像上时,它会平移 (没有点击/拖动)直到它到达终点

将 img 向左移动的等式如下: -1(相对鼠标位置)*(img width)/(container width)

这很好用,但它会在鼠标到达 img 末尾时留下一个空格。

Fiddle

$("figure img").mousemove( function (e) {
    var a = $(this).closest("figure"),
        b = $(this).width(),
        c = a.width(),
        d = (e.clientX - a.offset().left);
    $(this).css({
        left: -1*(d*b/c)
    }, 100);
});

有人可以帮忙吗?一旦鼠标到达终点,我希望 img 与容器的右侧完全对齐。

【问题讨论】:

    标签: javascript jquery html css image


    【解决方案1】:

    正确的公式是:-1 * (d/c) * (b - c)

    或者,更清楚地说:-1 * (mouseX / figureWidth) * (imgWidth - figureWidth)

    (mouseX / figureWidth) 表示鼠标所在图形宽度的百分比。它将是一个介于 0 和 1 之间的数字。

    (imgWidth - figureWidth) 表示您想用来将图像定位在另一侧的最大 X 值。

    将百分比乘以总移动范围可以得出当前鼠标位置的移动量!

    Updated Fiddle

    我建议使用更具描述性的变量名称,例如figureWidthimgWidthmouseX 等。不仅您更容易理解,而且人们也更容易回答。

    【讨论】:

      【解决方案2】:

      这应该可以工作:http://jsfiddle.net/0zd5t1wf/4/

      我只是得到图像左侧属性的限制值(图像宽度 - 图形框)

      $("figure img").each( function () {
          if($(this).width() >= ($(this).height() * 2.5)) {
              $(this)
                  .attr("class", "panorama")
                  .mousemove( function (e) {
                      var a = $(this).closest("figure"),
                          b = $(this).width(),
                          c = a.width(),
                          d = (e.clientX - a.offset().left),
                          newLeft = -1*(d*b/c),
                          limitValue = parseInt($(this).width()) - parseInt($("figure").width());
      
                      if ( newLeft < 0 && (newLeft *-1) < limitValue ){
                          $(this).css({
                              left: newLeft
                          }, 100);
                      }
                      $("#hello").html('why');
                  });
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2013-01-05
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        • 2011-05-26
        • 1970-01-01
        • 2011-10-24
        • 1970-01-01
        • 2013-01-07
        相关资源
        最近更新 更多