为什么当用户将鼠标悬停在图像上时图像不会更改?

时间:2019-01-09 15:23:15

标签: javascript angularjs

我正在尝试在鼠标悬停在图像上时缩放图像。第一次尝试显示zoomed image上的overlay。但是当我更改光标位置时 overlay或缩放图像无法显示更新的图像,为什么? 这是我的代码 https://plnkr.co/edit/CluSwaohUQbsveSPNz9L?p=preview

 $scope.zoomIn= function(event) {
  var element = document.getElementById("overlay");
  element.style.display = "inline-block";
  element.style.backgroundImage = 'url('+$scope.img+')'
  var img = document.getElementById("imgZoom");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition=(-posX*2)+"px "+(-posY*4)+"px";
   // $scope.$apply();
}

 $scope.zoomOut= function() {
  var element = document.getElementById("overlay");
  element.style.display = "none";
    //  $scope.$apply();
}

1 个答案:

答案 0 :(得分:0)

您的活动未聚焦,因为您没有使用angularjs的触发事件 代替onmousemove使用 ng-mousemove ,代替onmouseout使用 ng-mouseout

,在您调用的函数中,尝试仅使用angularjs函数,使用纯JavaScript可能会破坏angular的范围

这里是工作版本

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  
   $scope.zoomIn= function(event) {
  var element = document.getElementById("overlay");
  element.style.display = "inline-block";
  element.style.backgroundImage = 'url('+$scope.img+')'
  var img = document.getElementById("imgZoom");
  var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
  var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
  element.style.backgroundPosition=(-posX*2)+"px "+(-posY*4)+"px";
   // $scope.$apply();
}

 $scope.zoomOut= function() {
  var element = document.getElementById("overlay");
  element.style.display = "none";
    //  $scope.$apply();
}
  $scope.img = 'http://ginger-mum.com/wp-content/uploads/2015/10/3633-1269758855-0da5042c33400a811a5d766be4579cb8.jpg';
});
/* Put your css in here */

#overlay{
  border:1px solid black;
  width:350px;
  height:300px;
  display:inline-block;
  background-repeat:no-repeat;
  
}
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
<img id="imgZoom" 
width="300px" 
height="200px" 
ng-mousemove="zoomIn($event)" 
ng-mouseout="zoomOut()" 
src="{{img}}">
<br/>
<div id="overlay" ng-mousemove="zoomIn(event)"></div>
  </body>

</html>