使用angularjs用另一个图像替换一个图像

时间:2016-08-23 04:50:19

标签: javascript css angularjs html5

我想在考试结束时使用AngularJs和html替换我在线考试试卷上的图像。

在开始考试时,我已经在我的代码中使用 img id =“online_start”,我使用 css 将图片放入我的页面。

CSS:

  #online_start{
    background-image:url("start_exam.jpg");
    background-repeat:no-repeat;
    width:400px;
    height:150px;
    }

现在我想在考试结束时使用AngularJs替换另一个图像。

代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="layout.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {

  $scope.pos = 0, $scope.correct = 0, $scope.ques = true;

  $scope.questions = [
    ["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],

    ["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],

    ["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],

    ["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],

    ["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
  ];
  $scope.totalsecoriginal = $scope.totalsec = 60;
  $scope.totalsec--;
  $scope.min = parseInt($scope.totalsec / 60, 10);
  $scope.sec = $scope.totalsec - ($scope.min * 60);
  $scope.date = new Date();
  $scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
  $scope.currentTime = new Date();
  $scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
  function _(x) {
    console.log(angular.element(document.getElementById(x)));
    return angular.element(document.getElementById(x))[0];
  }
  $scope.interval = $interval(function() {
    if ($scope.sec === 0) {
      $scope.min--;
      $scope.sec = 60;
    }
    $scope.sec--;
  }, 1000);
  $scope.$watch('sec', function() {
    if ($scope.min === 0 && $scope.sec === 0) {
      $interval.cancel($scope.interval);
      window.alert('Time Up!!!');
      $scope.pos = $scope.questions.length;
      $scope.temp = true;
      $scope.renderQuestion();
    }
  })
  $scope.renderQuestion = function() {
    if ($scope.pos >= $scope.questions.length) {
    $scope.myBackgroundUrl = 'url(animatedthankyou.gif)';

      $scope.ques = false;
      if (!$scope.temp) { $scope.temp = false;
        $interval.cancel($scope.interval);
      }
      $scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
      $scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);

      $scope.pos = 0;
      return false;
    }
    $scope.question = $scope.questions[$scope.pos][0];
    $scope.chA = $scope.questions[$scope.pos][1];
    $scope.chB = $scope.questions[$scope.pos][2];
    $scope.chC = $scope.questions[$scope.pos][3];
  }
  $scope.checkAnswer = function() {
    $scope.choices = angular.element(document.getElementsByName('choices'));
    $scope.choice = -1;
    for (var i = 0; i < $scope.choices.length; i++) {
      if ($scope.choices[i].checked) {
        $scope.choice = $scope.choices[i].value;
        $scope.choices[i].checked = false;
      }
    }
    if ($scope.choice == $scope.questions[$scope.pos][4]) {
      $scope.correct++;
    }
    $scope.pos++;
    $scope.renderQuestion();
  }
  $scope.renderQuestion();

});

</script>
</head>
<body>
  <div id="Holder">
    <div id="Header"></div>
    <div id="NavBar">
<nav>
      <ul>
        <li><a href="Loginpage.htm"> Login</a></li>
        <li><a href="Registrationpage.htm">Registration</a></li>
      </ul>
    </div>
    <div id="Content">
      <div id="PageHeading">
        <h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
      </div>
      <div id="ContentLeft">
        <h2></h2>
        <br>
        <img id="online_start" ng-style="{background-image: myBackgroundUrl}">
        <br>
        <h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based 
examination system that provides an easy to use environment for both 
Test Conducters and Students appearing for Examination.</h6>
      </div>
      <div id="ContentRight">
        <section class="loginform_cf">
          <div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
            <table>
              <tr>
                <td id="test_status" style="text-align:left">
                  <h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
                  <h3 ng-hide='ques'>Test Completed  </h3>
                </td>
                <td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss">  </span> </td>
                <td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
              </tr>
              <tr>
                <td id="test" colspan="3">
                  <div ng-show="ques">
                    <h3>{{question}}</h3>
                    <input type='radio' name='choices' value='A'>{{chA}}
                    <br>
                    <input type='radio' name='choices' value='B'>{{chB}}
                    <br>
                    <input type='radio' name='choices' value='C'>{{chC}}
                    <br>
                    <br>
                    <button ng-click='checkAnswer()'>Next</button>
            <br>
            <br>
            Your Left Time is :{{min}} Minutes {{sec}} Seconds
                  </div>
                  <div ng-hide='ques'>
     <h3>You got {{correct}} correct of {{questions.length}} questions</h3>
     <h3> Your Grade :  {{showscore}}% </h3>
     <h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
     <button ng-click='EndExam()'>End the Exam</button>
                  </div>
                  <br>
                  <br>
                </td>
              </tr>
            </table>
          </div>
        </section>
      </div>
    </div>
    <div id="Footer"></div>
  </div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

在CSS中你放置一个background-image,在JS中你放置一个src

代替

document.getElementById("online_start").src = "animatedthankyou.gif";

document.getElementById("online_start").style.backgroundImag‌​e = "animatedthankyou.gif";

答案 1 :(得分:0)

AngularJS它不仅是一种使用花哨的中继器或魔术双重绑定的方法,它还允许通过不在控制器中执行DOM操作来清理你的JS代码(你正在做)。

你可以少花钱多办事。 Sse ng-style以编程方式更改您的背景图片网址:

-(void)mycontact
{
    NSMutableArray * contactNumbersArray = [[NSMutableArray alloc] init];

    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];

    if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted)
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:TRUE completion:nil];
        return;
    }

    CNContactStore *store = [[CNContactStore alloc] init];

    [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {

        if (granted == YES) {

            //keys with fetching properties

            NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];

            NSString *containerId = store.defaultContainerIdentifier;

            NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];

            NSError *error;

            NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];

            if (error) {

                NSLog(@"error fetching contacts %@", error);

            } else {

                NSString *phone;
                NSString *fullName;
                NSString *firstName;
                NSString *lastName;
                UIImage *profileImage;

                for (CNContact *contact in cnContacts) {

                    // copy data to my custom Contacts class.
                    firstName = contact.givenName;
                    lastName = contact.familyName;

                    if (lastName == nil) {
                        fullName=[NSString stringWithFormat:@"%@",firstName];
                    } else if (firstName == nil) {
                        fullName=[NSString stringWithFormat:@"%@",lastName];
                    } else {
                        fullName=[NSString stringWithFormat:@"%@ %@",firstName,lastName];
                    }

                    UIImage *image = [UIImage imageWithData:contact.imageData];
                    if (image != nil) {
                        profileImage = image;
                    }else{
                        profileImage = [UIImage imageNamed:@"person-icon.png"];
                    }

                    for (CNLabeledValue *label in contact.phoneNumbers) {

                        phone = [label.value stringValue];

                        if ([phone length] > 0) {
                            [contactNumbersArray addObject:phone];
                        }
                    }

                    NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,@"fullName",profileImage,@"userImage",phone,@"PhoneNumbers", nil];
                }

                dispatch_async(dispatch_get_main_queue(), ^{
                    for(int j=0;j<[contactNumbersArray count];j++)
                    {
                        NSString *newString = [[contactNumbersArray[j] componentsSeparatedByCharactersInSet:
                                                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
                                               componentsJoinedByString:@""];

                        contactNumbersArray[j]=newString;
                    }
                });
            }
        }

    }];
}

并在您的控制器中,根据需要更改背景:

<img id="online_start" ng-style="{background-image: myBackgroundUrl}">

更干净,不是吗?

答案 2 :(得分:0)

尝试:

 $scope.myBackgroundUrl = {'background-image': 'url(animatedthankyou.gif)'};

在HTML中,使用ng-controller将下面的行放在div中:

    <img id="online_start" ng-style="myBackgroundUrl">

请参阅:

  <!DOCTYPE html>
<html>
<head>
<meta charset="UFT-8">
<link rel="stylesheet" href="menu.css">
<link rel="stylesheet" href="layout.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function($scope, $compile, $window, $interval, $timeout, $filter) {

  $scope.pos = 0, $scope.correct = 0, $scope.ques = true;

  $scope.questions = [
    ["Which of the following a is not a keyword in Java ?", "class", "interface", "extends", "C"],

    ["Which of the following is an interface ?", "Thread", "Date", "Calender", "A"],

    ["Which company released Java Version 8 ?", "Sun", "Oracle", "Adobe", "A"],

    ["What is the length of Java datatype int ?", "32 bit", "16 bit", "None", "C"],

    ["What is the default value of Java datatype boolean?", "true", "false", "0", "A"]
  ];
  $scope.totalsecoriginal = $scope.totalsec = 60;
  $scope.totalsec--;
  $scope.min = parseInt($scope.totalsec / 60, 10);
  $scope.sec = $scope.totalsec - ($scope.min * 60);
  $scope.date = new Date();
  $scope.hhmmss = $filter('date')(new Date(), 'hh:mm:ss a');
  $scope.currentTime = new Date();
  $scope.currentTime.setSeconds($scope.currentTime.getSeconds() + 60);
  function _(x) {
    console.log(angular.element(document.getElementById(x)));
    return angular.element(document.getElementById(x))[0];
  }
  $scope.interval = $interval(function() {
    if ($scope.sec === 0) {
      $scope.min--;
      $scope.sec = 60;
    }
    $scope.sec--;
  }, 1000);
  $scope.$watch('sec', function() {
    if ($scope.min === 0 && $scope.sec === 0) {
      $interval.cancel($scope.interval);
      window.alert('Time Up!!!');
      $scope.pos = $scope.questions.length;
      $scope.temp = true;
      $scope.renderQuestion();
    }
  })
  $scope.renderQuestion = function() {
    if ($scope.pos >= $scope.questions.length) {
    $scope.myBackgroundUrl = {'background-image': 'url(animatedthankyou.gif)'};


      $scope.ques = false;
      if (!$scope.temp) { $scope.temp = false;
        $interval.cancel($scope.interval);
      }
      $scope.showscore = Math.round($scope.correct / $scope.questions.length * 100);
      $scope.minuteleft = parseInt(($scope.totalsecoriginal - $scope.totalsec) / 60, 10);

      $scope.pos = 0;
      return false;
    }
    $scope.question = $scope.questions[$scope.pos][0];
    $scope.chA = $scope.questions[$scope.pos][1];
    $scope.chB = $scope.questions[$scope.pos][2];
    $scope.chC = $scope.questions[$scope.pos][3];
  }
  $scope.checkAnswer = function() {
    $scope.choices = angular.element(document.getElementsByName('choices'));
    $scope.choice = -1;
    for (var i = 0; i < $scope.choices.length; i++) {
      if ($scope.choices[i].checked) {
        $scope.choice = $scope.choices[i].value;
        $scope.choices[i].checked = false;
      }
    }
    if ($scope.choice == $scope.questions[$scope.pos][4]) {
      $scope.correct++;
    }
    $scope.pos++;
    $scope.renderQuestion();
  }
  $scope.renderQuestion();

});

</script>
</head>
<body>
  <div id="Holder">
    <div id="Header"></div>
    <div id="NavBar">
<nav>
      <ul>
        <li><a href="Loginpage.htm"> Login</a></li>
        <li><a href="Registrationpage.htm">Registration</a></li>
      </ul>
    </div>
    <div id="Content">
      <div id="PageHeading">
        <h1><marquee direction="right" behavior="alternate">All the Best</marquee></h1>
      </div>
      <div id="ContentLeft">
        <h2></h2>
        <br>
        <br>
        <h6>Online Examination System(OES) is a Multiple Choice Questions(MCQ) based 
examination system that provides an easy to use environment for both 
Test Conducters and Students appearing for Examination.</h6>
      </div>
      <div id="ContentRight">
        <section class="loginform_cf">
          <div ng-app="MyApp" ng-controller="MyController" ng-init="StartTimer()">
<img id="online_start" ng-style="myBackgroundUrl">
            <table>
              <tr>
                <td id="test_status" style="text-align:left">
                  <h3 ng-show='ques'>Question {{pos+1}} of {{questions.length}}</h3>
                  <h3 ng-hide='ques'>Test Completed  </h3>
                </td>
                <td ng-show='ques'> Exam Starts :<span ng-bind="hhmmss">  </span> </td>
                <td ng-show='ques'> Exam Ends : {{currentTime | date:'hh:mm:ss a'}} </td>
              </tr>
              <tr>
                <td id="test" colspan="3">
                  <div ng-show="ques">
                    <h3>{{question}}</h3>
                    <input type='radio' name='choices' value='A'>{{chA}}
                    <br>
                    <input type='radio' name='choices' value='B'>{{chB}}
                    <br>
                    <input type='radio' name='choices' value='C'>{{chC}}
                    <br>
                    <br>
                    <button ng-click='checkAnswer()'>Next</button>
            <br>
            <br>
            Your Left Time is :{{min}} Minutes {{sec}} Seconds
                  </div>
                  <div ng-hide='ques'>
     <h3>You got {{correct}} correct of {{questions.length}} questions</h3>
     <h3> Your Grade :  {{showscore}}% </h3>
     <h4>Exam Finished in Time :{{minuteleft}} Minutes {{sec}} Seconds</h4>
     <button ng-click='EndExam()'>End the Exam</button>
                  </div>
                  <br>
                  <br>
                </td>
              </tr>
            </table>
          </div>
        </section>
      </div>
    </div>
    <div id="Footer"></div>
  </div>
</body>
</html>