我使用 jQuery
来交换两张图片的来源,这样,当您单击一张图片时,它的 src 将与作为数据属性添加的另一张图片交换,从而导致图片发生变化。我不想使用 angularjs 达到同样的效果。我没有严格的议程,它应该使用 src 交换技术本身来在 angularjs 中实现相同的目的。任何简单且有效的东西都很好。这是我现有的代码。
jQuery
$(".side-nav li:nth-child(2)").append("<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'>");
$("#arrowRotate").click(function() {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap", current);
//toggle li's below
$(".side-nav li:nth-child(3)").toggle();
$(".side-nav li:nth-child(4)").toggle();
$(".side_nav_custom li:nth-child(2) a").toggleClass("orangeSwap");
});
实现切换部分很容易,我已经在 Angular (see fiddle)中实现了它。唯一让我烦恼的是 src 交换部分。我已经设置了一个 plunker here.
Angular
index.html
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.4.0-beta.3" src="https://code.angularjs.org/1.4.0-beta.3/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="swap">
<div ng-controller="SwapControl">
<h1>Hello {{myData.names.nameTwo}}!</h1>
<img ng-click="myData.swapHere()" ng-src="{{myData.images.initialImage}}" alt="image to be swapped">
</div>
</body>
</html>
script.js
// Code goes here
var myApp = angular.module("swap", []);
myApp.controller('SwapControl', function($scope) {
$scope.myData = {};
$scope.myData.names = {
nameOne: "Plunker",
nameTwo: "Thomas"
};
$scope.myData.images = {
initialImage: "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif",
finalImage: "http://www.omniaceducation.com/Portals/11164/images/small-logo.jpg"
};
$scope.myData.swapHere = function() {
// swaping takes place here
};
});
最佳答案
再添加一个变量到myData.images
$scope.myData.images = {
initialImage: "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif",
finalImage: "http://www.omniaceducation.com/Portals/11164/images/small-logo.jpg",
current : "http://creativecurio.com/wp-content/uploads/2007/vm-logo-sm-1.gif"
};
你可以放
ng-src="{{myData.images.initialImage}}"
作为 ng-src="{{myData.images.current}}"
然后在你的交换函数中。
$scope.myData.swapHere = function() {
if($scope.myData.images.current === $scope.myData.images.finalImage)
$scope.myData.images.current = $scope.myData.images.initialImage
else if($scope.myData.images.current === $scope.myData.images.initialImage)
$scope.myData.images.current = $scope.myData.images.finalImage
};
关于javascript - 使用angularjs交换图像标签中的ng-src属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28404592/