【问题标题】:Enlarging images from the centre by percent?将图像从中心放大百分比?
【发布时间】:2012-01-30 19:57:36
【问题描述】:

对于使用 jQuery 的网站,页面上有图形,当点击这些图形时,会在网站的另一部分显示信息。当鼠标悬停时,图像会从它们的中心扩大一个百分比。问题是当您快速进出鼠标时(在动画完成之前),图像无法正确调整大小。 (它们变小了。)

    $(".locationimg").hover(
        function(){
            var height = $(this).height()
            var width = $(this).width()
            var top = $(this).position().top
            var left = $(this).position().left
            $(this).stop().animate({
                height: height*1.1 + 'px',
                width: width*1.1 + 'px',
                top: top - (((height*1.1)-height)/2) + 'px',
                left: left - (((width*1.1)-width)/2) + 'px'
            });
        },
        function(){
            var height = $(this).height()
            var width = $(this).width()
            var top = $(this).position().top
            var left = $(this).position().left
            var height1 = height/1.1
            var width1 = width/1.1
            $(this).stop().animate({
                height: height1 + 'px',
                width: width1 + 'px',
                top: top - (((height1)-height)/2) + 'px',
                left: left - (((width1)-width)/2) + 'px'
            });
        }
    );

如果可以在进入 .hover() 之前定义变量,这将很容易,因为调整图像大小将只是“高度:高度”等等。这样做的问题是有几个图像都需要这样做,因此需要在 .hover() 中定义变量。

【问题讨论】:

    标签: jquery resize hover jquery-animate var


    【解决方案1】:

    尝试使用stop(false, true) 而不是仅使用stop()。这意味着动画将在新动画开始之前“完成”。

    此外,您可以使用data() 函数存储元素的高度和宽度。

    【讨论】:

      【解决方案2】:

      在 hover() 之前,您可以将原始和缩放后的尺寸和位置存储在图像本身的数据属性中:

      $(".locationimg").each(function() {
          var $this      = $(this),
              origWidth  = $this.width(), 
              origHeight = $this.height(), 
              zoomWidth  = origWidth * 1.1,
              zoomHeight = origHeight * 1.1,
              pos        = $this.position(),
              origTop    = pos.top,
              origLeft   = pos.left
              // ... also find zoomed top, left...
          ;
          $this.data({
              "origwidth":  origWidth,
              "origHeight": origHeight,
              "zoomWidth":  zoomWidth,
              "zoomHeight": zoomHeight
              /* etc. */
              /* ... also store top and left... */
          });
      }).hover(
          // your hover code here
      )
      

      然后在悬停处理程序中,您可以只读取已经存储的尺寸/位置,然后在鼠标悬停时转换到缩放的尺寸/位置,或者在鼠标悬停时转换到原始尺寸/位置,而不是尝试即时计算。这也会快很多。

      【讨论】:

        猜你喜欢
        • 2016-12-04
        • 1970-01-01
        • 2020-08-09
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 2012-01-04
        • 1970-01-01
        相关资源
        最近更新 更多