简体   繁体   English

通过javascript更改html DOM没有响应

[英]changing the html DOM via javascript not responding

I am changing the background of a div with a function. 我正在使用功能更改div的背景。 The following is my html code: 以下是我的html代码:

$scope.Background = 'img/seg5en.png';
document.getElementById("Bstyle").style.background = "url("+$scope.Background+") no-repeat center fixed;";           
console.log(document.getElementById("Bstyle").style.background);
console.log("url("+$scope.Background+") no-repeat center fixed;");

Originally, $scope.Background is equal to " img/bg.png " which is specified on top of my document. 最初, $scope.Background等于在我的文档顶部指定的“ img/bg.png ”。 The first console.log prints that the value of style.background as " img/bg.png ". 第一个console.log将style.background的值打印为“ img/bg.png ”。

However, the second console.log prints: url(img/seg5en.png) no-repeat center fixed . 但是,第二个console.log打印: url(img/seg5en.png) no-repeat center fixed

I do not understand why my html page does not update though. 我不明白为什么我的HTML页面没有更新。

Please change DOM using angularised way 请使用成角度的方式更改DOM

Use ng-style to change style of element from JavaScript. 使用ng-style从JavaScript更改元素的样式。

In angular you can assign value to $scope variable and it can be access to your view. 在angular中,您可以为$ scope变量赋值,并且可以访问您的视图。

Here is demo for resolve your issue 这是解决您的问题的演示

 function ChangeBackground($scope) { $scope.Background = 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQdNIsxlrqB0Bqy-qmamo6tt9fdqqL9p43Bf5oy11xt0UuAa9vAILYjMX7_'; $scope.changeImage = function(){ $scope.Background ='https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQ2I2AW0JI-scAY0Phe321d1Yi8UHbFhsIk8OXTbpfEfaNf9F4V9lt60rs'; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="ChangeBackground"> <div ng-style="{'background': 'url(' + Background + ')'}" > Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla porttitor mi non consequat varius. Curabitur libero tellus, placerat in metus nec, porttitor facilisis mi. Vivamus nec mattis felis. Cras mattis in mi sed feugiat. Sed ut hendrerit nisi, at tincidunt nibh. Donec vel malesuada orci. Nunc auctor tortor in mi consectetur gravida. Phasellus eleifend erat lectus, convallis tincidunt nisi euismod et. Donec a ornare eros, et eleifend magna. Phasellus viverra pellentesque metus, in lacinia tortor egestas nec. Suspendisse luctus dolor sit amet nisi interdum, nec commodo orci consectetur. Phasellus pretium vulputate viverra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. </div> <input type="button" value="Change Background" ng-click="changeImage()"/> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM