将图像缩放到中心jquery或javascript

时间:2016-07-19 07:31:10

标签: javascript jquery html

如果我缩放图像,它将向右移动。这是我下面的js函数。当我缩放图像时,背景的实际宽度和高度是恒定的,只有背景尺寸应该是动态的。这就是为什么看起来如果它变焦它会向右移动而不是在中心的原因。我想要的是当我缩放图像时,它将其向前缩放到图像的中心。

<button ng-click="remItem(x,$index);" > Remove</button>

$scope.remItem = function(x,index){
    $scope.emplist.splice(index,1);
}

2 个答案:

答案 0 :(得分:1)

如果您的图像是方形的,这应该有效:它会偏移背景图像,使其中心保持在包含元素的中心。

var posx = (el.width()-wid)/2;
var posy = (el.height()-wid)/2;
el.css({
        'background-size': wid + 'px auto',
        'background-position': posx +'px ' +posy +'px'
    });

答案 1 :(得分:0)

对我有用的是将容器元素滚动一半,即增加图像的宽度和高度的一半。为此,您可以使用scrollBy。例如。如果您的容器元素是el并且其中的图像是img。现在,如果您要将宽度和高度增加当前'x'px的10%,将高度增加'y'px,则要放大,您的放大功能如下所示:

function zoomIn() {
  let imgWidth = img.width.replace(/px/g,"");  // removing 'px'
  let imgHeight = img.height.replace(/px/g,"");  // removing 'px'
  let x = imgWidth + (imgWidth*0.1);
  let y = imgHeight + (imgHeight*0.1);
  el.scrollBy(x/2, y/2);
}